Skip to content Skip to sidebar Skip to footer

Learn to Create Loops in PHP

Looping is a command that functions to do something repeatedly using program code. For example, if you want to print a number from 1 to 10, then we don’t need to manually write it in the program code from numbers 1 to 10. Just write the syntax once, the looping process will be able to display numbers from 1 to 10.

Also read: How to Install XAMPP and WordPress on Localhost

Looping in php is almost the same as looping in C, C++ and their derivatives. There are three types of repetition, namely for, while, do-while. Immediately, here’s how:

Video Tutorials

";	}?>


The output of the code above is the words “Will display the loop for 1 to 10”. The explanation of the statement in the for is that first we declare the value of the variable $i equal to 1 ($i = 1). Then if the value of the variable $i is less than equal to 10 ($i <= 10), then the loop will continue to run. The last one is increment variable $i ($i++), meaning that every time it loops, the value of the variable $i is added by 1.

";		$i++;	}?>


Almost the same as the for loop, namely the initialization of the variable $i=1, then the condition $i <= 10, and also the increment $i++. The difference is the layout of the placement. The output is the sentence "learn the while loop from 1 to 10".

";		$i++;	}while($i<=10)?>


The purpose of the code above is to do (do) the command that is in while (while) the condition has not been met ($i <= 10). It's similar to the While loop, where in the While brackets are the conditions that haven't been met ($i <= 10).

How about looping for an array? It’s okay to use for, while, do-while loops in arrays, but it will take a little longer. Therefore to make it easier we use a foreach loop for arrays.

The explanation is like this, the foreach loop doesn’t need to specify an initial value and an ending value. That’s the advantage, we can complete the entire loop without setting the limit first.

  • Loop indexed array
";	}?>


$example is an indexed array. The purpose of the syntax in the foreach brackets is to replace the $example variable into the $email variable ($example as $email). Then echo is displaying the $email variable.

  • Associative array loop
 'satrio', 'umur'=>'24'];	foreach($contoh as $key=>$value){		echo "mahasiswa dengan $key $value 
"; }?>


An associative array is an array whose variables have keys. ‘name’ and ‘age’ are keys while ‘satrio’ and ’24’ are values, where $key is before the arrow – and $value is after the arrow -. The foreach loop above means changing the $example variable to $key and $value. Then display it with the echo command.

Php is indeed quite difficult, but if there is an intention then it can be fun. Hope you can understand it. Keep it up, don’t forget to share if you find it useful.