PHP foreach loop tutorial


Home - Tutorials - Basics

In this tutorial you will learn how to use the foreach loop in PHP.

Tutorial info:


Name:PHP foreach loop tutorial
Total steps:2
Category:Basics
Level:Beginner

Bookmark PHP foreach loop tutorial



Bookmark and Share

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) statement
It 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:
Code:
  1. $test = array(1,2,3,4,5,6,7,8,9,10);
  2.  
  3. foreach ($test as $value) {
  4. echo "$value - ";
  5. }
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:
  1. // Creat the test array
  2. $test = array(1,2,3,4,5,6,7,8,9,10);
  3.  
  4. // Modify the array content as we use reference variable
  5. foreach ($test as &$value) {
  6. $value = $value*2;
  7. }
  8.  
  9. // Display the array
  10. foreach ($test as &$value) {
  11. echo "$value - ";
  12. }
In the next step you will see how to display an associative array with foreach.





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


Follow phpf1 on Twitter




F1 Site Family
AJAX F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0727