Today's topic in our PHP best approaches series: Loops in PHP. How to write a quality PHP loop? What are the tricks of coding loops in PHP? Let's find out together.

What is PHP Loop?

PHP loops are frequently used to operate on data sets and repeat blocks of code. However, inefficient use of loops can significantly affect the performance of the script. In this article, we will share best practices and examples on the performant and effective use of loops in PHP.

PHP Loop Examples

If you are not familiar with PHP loops, first: PHP lessons You should examine the examples we have prepared for you about cycles from our series.

Choose the Right Loop Type

It is necessary to choose a loop suitable for the operation to be performed in PHP language. The For or Foreach loop is not suitable for every operation! Now let's understand this with examples of correct and incorrect usage.

PHP For Loop

PHP for loop is the right choice for iterating with numbers.

Correct Use: Ideal for situations where the number of iterations is predetermined.

for ($i = 0; $i < 10; $i++) {
    echo "Number: " . $i . "<br>";
}

Misuse: To iterate over an array or without an iteration number for use cycle.

for ($i = 0; $i < count($array); $i++) {
    // For döngüsü bunun için ideal bir çözüm değil. BUNU YAPMAYIN!
}

PHP Foreach Loop

PHP foreach The loop is ideal for iterating over arrays.

Correct Use: Automatically iterates over each element of the array.

$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo "Color: " . $color . "<br>";
}

Misuse: foreach When using a non-array data structure or when index-based iteration is required.

foreach ($i = 0; $i < 10; $i++) {
    // Forach döngüsü bunun için ideal bir çözüm değil. BUNU YAPMAYIN!
}

PHP While Loop

PHP while loop in PHP in certain cases for and foreach It may be more suitable depending on the cycles. The most important detail is the scenarios in which the continuation condition of the loop may change within the loop.

Correct Use: Ideal for situations where the condition needs to be checked inside the loop.

$i = 0;
while ($i < 10) {
    echo "Sayı: " . $i . "<br>";
    $i++;
}

Misuse: Cases where the loop condition never changes

$counter = 0;
while ($counter < 10) {
    echo "Sayı: " . $counter . "<br>";
    // Sonsuz döngü (infinite loop) oluşacak. BUNU YAPMAYIN!
}

Using PHP Loops Effectively and Performance

Never Call a Function in a Loop

Repeatedly calling the same function within the loop can negatively impact performance, especially when working with large data sets. Never call functions in loops. This will make your code smell

To learn the meanings and differences of smell code and clean code clean code You can read our article

Misuse

count() Calling functions like in a loop.

for ($i = 0; $i < count($array); $i++) {
    // yapılacak işlemler
}

Correct Use

Call functions outside the loop to avoid unnecessary recalculations.

$array_len = count($array);
for ($i = 0; $i < $array_len; $i++) {
    // yapılacak işlemler
}

This approach count() It prevents the function from being re-executed at each iteration, thus making the loop more efficient.

Don't Use Queries and Heavy Operations in Loops

In PHP, especially when working with large data sets, using queries and operations that may cause performance problems in a loop causes major performance problems and excessive resource consumption.

Misuse

In this example, the database query is used in a foreach loop. A separate query runs for each user at each iteration, causing serious performance problems.

foreach ($users as $user) {
    $userData = $database->query("SELECT * FROM user_data WHERE user_id = " . $user->id);
    // BUNU ASLA YAPMAYIN!
}

Correct Use

In this example, all necessary data is received outside the loop with an optimized SQL query, and the data received is processed within the loop. The loop only operates on data retrieved from the database, thus minimizing the number of queries made in each iteration.

$userIds = array_map(function($user) { return $user->id; }, $users);
$userData = $database->query("SELECT * FROM user_data WHERE user_id IN (" . implode(',', $userIds) . ")");

foreach ($userData as $data) {
    // veritabanından alınan verileri işle
}

PHP Loops

Performance and effective use of PHP loops increases the efficiency of the code, optimizes resource usage and prevents potential performance problems. Choosing the right loop types, increasing efficiency in loops, and paying attention to resource management are key approaches that will help you achieve better results when using PHP loops. By applying these approaches, you can make your codes faster, cleaner and more readable.