×
☰ See All Chapters

PHP Iteration Statements

Iteration statements are also called as looping statements. By default all statements are executed sequentially in java program. Iteration statements are used to repeat the statements until specified condition is met.

In PHP, we have the following looping statements:

  • while  

  • do...while 

  • for  

  • foreach 

while loop

while loop syntax

while(condition)

{

        statement(s);

}

The statement(s) will be executed as long as condition evaluates to true. statement(s) may be a single statement or a block of statements.

The value of the variable involved in condition should be changing during every pass of the while loop. If it is not changed, then the while loop enters into an infinite loop.

do-while

do-while syntax

do {

        statement(s);

} while (condition);

statement(s) will be executed once. Then the condition will be evaluated, if it evaluates to true the do block will be executed again. This process repeats until the given condition becomes false.  statement(s) may be a single statement or a block of statements

The value of the variable involved in condition should be changing during every pass of the while loop. If it is not changed, then the while loop enters into an infinite loop.

for loop

for loop syntax

for (initialization; boolean_expression; update_statement)

{

       //body of the loop;

}

for statement has the following properties:

  • The two semicolons are required and create three sections: an initialization statement, a boolean expression, and an update statement. 

  • The initialization step occurs once at the beginning of the loop. 

  • The boolean_expression must evaluate to true or false. 

  • The initialization and update_statement sections can contain multiple statements, separated by commas. 

  • Any variables declared in the initialization step are local variables in for loop and go out of scope when the loop finishes. 

Below is the flow of control in for loop:

  • The initialization statement is executed first, and only once. This step allows you to declare and initialize any loop control variables.  

  • Next, the condition (boolean_expression) is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after for loop. 

  • After the body of for loop executes the flow of control jumps back up to the update_statement. This statement allows you to update any loop control variables.  

  • The condition (boolean_expression) is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, for loop terminates. 

for loop example

<?php

for ($i=1; $i<=5; $i++)

{

    echo "The number is " . $i . "<br />";

}

?>

php-iteration-statements-0
 

foreach loop

The foreach loop is used to loop through arrays.

foreach ($array as $value)

{

    //code to be executed;

}

  • The $array must be an array. 

  • $value receives the value from $array one at a time, from beginning to end. 

  • The scope of the $value is the body of the loop. 

  • The number of iterations of the loop equals the size of the $array. If the $array is empty, the body of the loop does not execute.  

foreach loop example

<?php

$x=array("one","two","three");

foreach ($x as $value)

{

    echo $value . "<br />";

}

?>

php-iteration-statements-1
 

PHP Iterables

The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function arguments and function return values.

<?php

function printIterable(iterable $myIterable) {

    foreach($myIterable as $item) {

        echo $item;

    }

}

 

$arr = ["1", "2", "3"];

printIterable($arr);

 

function getIterable():iterable {

    return ["1", "2", "3"];

}

 

$myIterable = getIterable();

foreach($myIterable as $item) {

    echo $item;

}

?>

Creating Custom Iterables

By default All arrays are iterables, so any array can be used as an argument of a function that requires an iterable. To create custom iterable you have to implement Iterator interface and implement below methods. (You will learn about class and Interface in later chapters.)

  • current() - Returns the element that the pointer is currently pointing to. It can be any data type 

  • key() Returns the key associated with the current element in the list. It can only be an integer, float, boolean or string 

  • next() Moves the pointer to the next element in the list 

  • rewind() Moves the pointer to the first element in the list 

  • valid() If the internal pointer is not pointing to any element (for example, if next() was called at the end of the list), this should return false. It returns true in any other case 

<?php

class CustomIterator implements Iterator {

    private $items = [];

    private $pointer = 0;

   

    public function __construct($items) {

        $this->items = array_values($items);

    }

   

    public function current() {

        return $this->items[$this->pointer];

    }

   

    public function key() {

        return $this->pointer;

    }

   

    public function next() {

        $this->pointer++;

    }

   

    public function rewind() {

        $this->pointer = 0;

    }

   

    public function valid() {

        return $this->pointer < count($this->items);

    }

}

 

function printIterable(iterable $myIterable) {

    foreach($myIterable as $item) {

        echo $item;

    }

}

 

$iterator = new CustomIterator(["1", "2", "3"]);

printIterable($iterator);

?>

 


All Chapters
Author