PHP foreach Loop

PHP foreach Loop with Example

PHP foreach loop is used to loop through the associative arrays.

Syntax:

  • $array = associative array.
  • $key = array key.
  • &value = array keys value.

$key and $value variables can be named anything. The $key will be equal to the arrays key, and $value will be equal to that key`s value.

The loop ends when the last array key (=>) value pair reached.

Associative Array Example:

Associative array have named keys. The key names are placed inside single or double quotes and the (=>) is used to assign key value pairs.

Output:

  • In the above program, we are using an associative array here $students with three keys/values, and we are printing the value of each array element through a foreach loop and an echo function for printing results.

Example2:

Output:

  • In the above program, an array of$fruits contains three elements. For each loop iteration, here the value of current array element is assigning to the variable $t, an array pointer is moving by one and displaying the value of each array element until the last array element found.

Example3:

Output:

  • In the above program, we are using a user-defined function sub, and the function body is containing an array $s with four elements, and we are displaying the value of each array element using a foreach loop.

Example4:

Output:

  • In the above, program is containing a user-defined function fruit, and an array is passing as an argument to the function. The function is containing a foreach loop, through this loop we are displaying the value of each array element with an echo statement. When a function is called, then the function body will be executed.