PHP foreach loop tutorial
In this tutorial you will learn how to use the foreach loop in PHP.
Step 1 - Foreach basics
PHP foreach loop tutorial
The foreach loop is a bit special control structure. Foreach was designed to iterate over an array and you can use it only for array variables.
The syntax is the following:
foreach (array_expression as $value) statementIt means that the foreach loop iterates over an array and in each iteration it copies the actual array value to the $value variable. You can so use it in your statement. A real example looks like this:
The $value is a new variable so if you change it's value then the value in the array will not be changed. If you want to to this you need to use reference variables as follows:
Code:
// Creat the test array // Modify the array content as we use reference variable foreach ($test as &$value) { $value = $value*2; } // Display the array foreach ($test as &$value) { echo "$value - "; }
Next Step of PHP foreach loop tutorial
Tags: php foreach loop, php foreach, foreach loop, php loop, foreach, loop, php
| PHP foreach loop tutorial - Table of contents |
|---|
| Step 1 - Foreach basics |
| Step 2 - Foreach for associative arrays |