Skip to content
Home » Using while vs foreach loop Correctly: 5 PHP Code Examples (2023)

Using while vs foreach loop Correctly: 5 PHP Code Examples (2023)

Summary

There are 3 popular loops available for php arrays - foreach, for, & while. The type of loop that you should use is dependent on your use case. Use the foreach when you need to loop through everything, for loops when iterating a number and use while loops for conditional requirements.




The while and foreach loop are among the several loops in PHP. A loop executes a block of code repeatedly. Then why do we have all these different types if they do the same job? That’s a good question, and the answer is that while they inherently do the same job, some loops fit well for a particular use case. 


This statement might sound a little abstract at this point. This article will explore when to use while vs foreach loop in PHP. By the end of this article, you’ll understand how one loop fits a specific job better than the other. So, let’s move on to the article.

When to use while vs foreach loop in PHP – while loop 

We’ve already seen details of the while loop in one of the articles. Here’s a review.

Description

While loop checks a boolean condition on entry. If the condition is true, it executes the body. After the first run, it rechecks the condition. The loop continues as long as the condition is true. Here’s the syntax of the while loop.

Syntax

while(condition)
{
   //While loop BODY
}

The condition is a boolean statement that evaluates to either true or false.

Flow Chart

Flow charts are intuitive graphical representations of a code. Here’s the flow chart of a while loop.

When to use while vs foreach loop in PHP

Example

The example here clarifies the significance of the boolean condition in a while loop. As long as the condition holds, the loop iterates.

<?php
$i = 0;
 
//Loop as long as $i is less than or equal to 10.
while($i <= 10)
{
    echo $i.PHP_EOL;
    $i++; //Increment $i by 1.
}
 
 
/*
OUTPUT
0
1
2
3
4
5
6
7
8
9
10
*/
?>

As soon as the boolean condition evaluates the false, the loop stops. So, while the loop is all about the boolean condition. How’s that different than a foreach loop?

When to use while vs foreach loop in PHP – foreach loop

Description

The foreach loop is specialized for iterating over an array or object, abstractly called iterables. The pointer moves on until it reaches the end of an iterable. The foreach loop then ends after the end of the iterable.

The foreach loop works really well with PHP associative arrays. It keeps a pointer to the array’s values and keys. The foreach loop doesn’t stop until the pointer reaches the end of the array. That’s why the foreach loop is ideal for looping over associative arrays in PHP.

Note that the foreach loops throw an error if you pass data types other than arrays or objects.

Syntax#1

Here’s the syntax if you want to iterate over an array’s values only. The $value gets the value one by one as the foreach loops through an array.

foreach(iterable as $value)
{
  //foreach loop BODY
}

Syntax#2

Here’s the syntax if you want to iterate over an array’s values as well as keys. Here the $key gets the key, and $value gets the value one by one as the foreach loops through the array.

foreach(iterable as $key => $value)
{
  //foreach loop BODY
}

Flowchart

Here’s a flowchart for the foreach loop.

Example

The example uses an array with employee names as array keys and their salaries as array values. We’ll use a foreach loop to increment employees’ salaries by 1000 USD.

<?php
$employee_salary = array(
    "Richard" => 10000,
    "Daniel"  => 9000,
    "Kylie"   => 8000,
    "Mona"    => 7000,
    "Leo"     => 6000,
    "Adam"    => 5000
);
 
 
//Loop over and get the salary as value.
foreach($employee_salary as $employee => $salary)
{
    //Increment a 1000$ to employees' salaries
    $employee_salary[$employee] = $salary + 1000;
}
 
 
print_r($employee_salary);
 
 
/*OUTPUT
Array
(
    [Richard] => 11000
    [Daniel] => 10000
    [Kylie] => 9000
    [Mona] => 8000
    [Leo] => 7000
    [Adam] => 6000
)
*/
?>

Check out the foreach loop. It is really convenient to index the array based on the key because the foreach references the key as it loops through. Remember that it isn’t a hard and fast rule to do $key => $value in the foreach. We have used $employee => $salary for more clarity.

Now let’s jump back to the question of when to use while vs foreach loop in PHP?

When to use while vs foreach loop in PHP

We’ve seen examples in the while loop and foreach loop sections. As a matter of fact, you cannot iterate the array we’ve seen in the foreach loop example as quickly and conveniently using the while loop. We’re not implying that it is impossible, but doing that through a while loop will be quite a mess. You might need some additional function calls. 

Similarly, the example we did in the while loop section isn’t meant for the foreach loop. Hence it is just as the saying goes, “To each his own.” Remember, a refactored and a shortened code is always superior to a code with many useless function calls. 

So, when you have an array to loop over, then go for the foreach loop. Whenever you have a boolean condition for a loop, go for the while loop. That’s a take for this article. We hope that you’ve enjoyed this article. Stay tuned for more exciting PHP articles.

Learn More About Loops in PHP

Want to learn how to use loops in PHP? This article is part of our series on looping through PHP arrays. Check out our full series to become a PHP array loop ninja.

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started