What are some common methods for optimizing PHP code performance to reduce script execution time?

One common method for optimizing PHP code performance is to minimize the number of database queries by using efficient queries and caching results when possible. Another approach is to reduce the use of loops and nested loops in favor of more efficient array functions. Additionally, optimizing code by using built-in PHP functions and avoiding unnecessary function calls can also help reduce script execution time.

// Example of minimizing database queries by caching results
$cache_key = 'cached_data';
$cached_data = apc_fetch($cache_key);
if(!$cached_data){
    $result = mysqli_query($conn, "SELECT * FROM table");
    $cached_data = mysqli_fetch_all($result, MYSQLI_ASSOC);
    apc_store($cache_key, $cached_data, 3600); // Cache data for 1 hour
}

// Example of using array functions instead of loops
$numbers = range(1, 1000);
// Using array_map to square each number
$squared_numbers = array_map(function($num){
    return $num * $num;
}, $numbers);

// Example of optimizing code by using built-in PHP functions
$numbers = range(1, 1000);
// Using array_sum to calculate sum of numbers
$sum = array_sum($numbers);