PHP  while Loops

PHP while Loops are repeatedly executed when the condition returns true.The code will loop out when the condition returns false.

PHP while Loops

Usually,as a programmer you will need to execute a  certain code block severally.Without loops,one will be required to copy paste the same code severally to complete the tast,but with PHP Loops you can easily perform these task with less code.

Following are PHP Looping Statements

1.foreach-this statement is used to loop through a code using elements in  an array

2.for-used to loop through code for a certain number of times.

3.do…while-this statement will loop the code for the first time and it will repeat if the condition  returns true.

4.while-this statement will loop through a certain block of code severally.It will continue if the condition returns true.

See also:PHP Conditional Statements

PHP while Loop

While  loop executes  a certain block of code severally  and checks  condition.If it returns true,the code block is executed again.

PHP while syntax

while (condition returns  true) {
    code is  executed;
}

Example

<?php
$y = 0;

while($y<= 10) {
echo "Value of Y is : $y <br>";
$y++;
}
?>

 

PHP do…while Loop

PHP do…while loop will run a certain code for once and check condition again.If it returns true,the block of code will run again

Syntax

do {
    code to be run;
} while (condition is checked);

Example

<?php
$y = 0;

do {
echo "Number is : $y <br>";
$y++;
} while ($y<= 10);
?>

PHP  for Loops

PHP for loops runs a certain code block for a number of times specified.

PHP for loops  General syntax

for (initial counter; testing  counter; incrementing counter) {
  code block to be run;
}

Parameters in PHP for loops:

  • initial counter-starts the loop with a certain value that is incremented
  • testing  counter-Checks  the value and if true value is returned,the loop.
  • Incrementing  counter-The testing counter is increased

See below example that prints numbers 0 to 10:

<?php
for ($y = 0; $y<= 10; $y++) {
echo "Number is : $y <br>";
}
?>

PHP foreach Loop

The foreach loop are used to work only on arrays.They loop through the values in array

PHP foreach loop  general Syntax

foreach ($arr as $value) {
block executed to be executed.
}

Example

<?php
$animals = array("goat", "cow", "cat", "chicken");

foreach ($animals as $name) {
echo "$name <br>";
}
?>

Next Lesson:PHP Functions

About the Author: Eric K

My name is Eric.Am a software developer with skills in Php,Mysql, Java , Android,Node.js Above all, I have certification in Cisco Networking Associate (CCNA) and holds degree in Information Technology. Hire me: Email : kawi3462@gmail.com