PHP Tutorials

PHP While Loop Tutorial: Repeat Code Until a Condition Ends

Understand the PHP while loop with simple examples. See how the condition controls repetition and how to stop infinite loops before they break your page.

Serhat ALPASLAN2 min read

PHP

Understanding the PHP while loop is actually very easy if you already know how to use IF in PHP. Because the only difference is that the loop keeps going until the condition inside the while becomes TRUE.

while(koşul){
  //it will keep going as long as the condition is true.
}

In the example below, we’ll print the numbers from 1 to 10.

<?php
$baslangic = 0;
while ($baslangic < 10 ){
    echo  $baslangic++.'--';
}

We understood the example above, but let’s also look at how a while example works with an array.

<?php
$arr = array('a','b','c','d','e');
$arrLenght = count($arr);
$i=0;

while ($i < $arrLenght ){
    echo $arr[$i].'-';
    $i++;
}

In the example above, we looped through the elements in the array with while and printed each element to the screen one by one. Now let’s look at the while loop in a different way. If the condition part of a while loop is written incorrectly, you can create an infinite loop. But could there be situations where we actually need an infinite loop? Yes, sometimes there can be — that is, if you’ve written an application running in the background and you want it to keep running until a value inside the loop changes, you may need a loop like this.

while(true){
echo 'test-';
//this is an infinite loop. 
}

Share it if it helped

Write a comment