What are some best practices for optimizing PHP code for faster loading times?

One best practice for optimizing PHP code for faster loading times is to minimize the number of database queries by fetching only the necessary data. Another tip is to use caching mechanisms like APC or Memcached to store frequently accessed data and reduce server load. Additionally, optimizing loops and functions by avoiding unnecessary calculations and using efficient algorithms can also improve performance.

// Example of minimizing database queries by fetching only the necessary data
$query = "SELECT id, name FROM users WHERE id = :user_id";
$stmt = $pdo->prepare($query);
$stmt->execute(['user_id' => $user_id]);
$user = $stmt->fetch();

// Example of using caching mechanisms like APC
$key = 'user_' . $user_id;
if ($cached_data = apc_fetch($key)) {
    $user = $cached_data;
} else {
    // Fetch user data from the database
    $user = getUserData($user_id);
    apc_store($key, $user, 3600); // Cache data for 1 hour
}

// Example of optimizing loops and functions
$sum = 0;
for ($i = 0; $i < 1000; $i++) {
    $sum += $i;
}
echo $sum;