Understand PHP foreach as Statement (Not foreach in): Traverse PHP Array – PHP Tutorial

By | May 28, 2020

To traverse a php array, we can use for or foreach statement. As to foreach statement, it is much easier than for statement. In this tutorial, we will write some examples to show php beginners on how to use foreach statement.

Syntax

As to foreach statement, we can use it as follow:

foreach($arr as $key=>$value){
}

or

foreach($arr as $value){
}

here $arr is a php array.

You should notice, the full statement is foreach as, is not foreach in or for in.

You can not use these statements.

for($value in $arr){
}

or

foreach($a in $arr){
}

Both of them are wrong.

How to traverse a php array?

As to a normal php array, we can traverse it like this:

<?php
$data = array("Apple", "Orange", "Banana");

foreach($data as $value){
	echo $value."\n";
}
?>

Run this php script, you will get the result.

Apple
Orange
Banana

You also can do as follow:

foreach($data as $key=>$value){
	echo $key."-->".$value."\n";
}

The result is:

0-->Apple
1-->Orange
2-->Banana

As to associative array, we also can traverse it by foreach as statement.

Here is an example:

$data = array("fruit 1" => "Apple", "fruit 2" => "Orange", "fruit 3" => "Banana");
foreach($data as $value){
	echo $value."\n";
}

Run this code, you will get the result.

Apple
Orange
Banana

From the result, we can find: if we do not get key in foreach as statement, the value of associative array will be traversed.

We also can get the key and value of associative array.

foreach($data as $key=>$value){
	echo $key."-->".$value."\n";
}

The result will be:

fruit 1-->Apple
fruit 2-->Orange
fruit 3-->Banana
Category: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *