Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

How to use foreach in PHP

Dario Vincenzo Tarantini

We can iterate over an array (or even objects) in PHP using the foreach construct. In this shot, we will see how to use this construct over arrays.

This construct is useful when we need to iterate without knowing the size of the array.

Syntax

foreach can be used in two ways:

foreach($array as $key => $value;
//OR
foreach($array as $value).

Let’s see the differences.

1.$key => $value

If we specify the $key, we can view the specified key along with the elements. Otherwise, the index of the element is shown alongside the element value. This works with both one-dimensional and multi-dimensional arrays.
Let’s see an example:

<?php
// first, we need to declare two array
$arr1 = [1, 2, 3, 4, 5]; 
$arr2 = [
  "key1" => 1,
  "key2" => 2,
  "key3" => 3,
  "key4" => 4,
  "key5" => 5,
];
// print the first array
foreach($arr1 as $key => $value){
  echo $key . " => " . $value . "\n";
}
// print the second array
foreach($arr2 as $key => $value){
  echo $key . " => " . $value . "\n";
}

In the first case, we iterated over an array with numeric indexes. In the second case, we iterated over an array with key-value pairs.

2.$value

If we omit the $key, we will only be able to see the value of the array. The usage is similar to the previous one:

<?php
// first, we need to declare two array
$arr1 = [1, 2, 3, 4, 5]; 
$arr2 = [
  "key1" => 1,
  "key2" => 2,
  "key3" => 3,
  "key4" => 4,
  "key5" => 5,
];
// print the first array
foreach($arr1 as $value){
  echo $value . "\n";
}
echo "--\n"; 
// print the second array
foreach($arr2 as $value){
  echo $value . "\n";
}

You can see that the output is the same since the arrays have the same values.

RELATED TAGS

php
communitycreator

CONTRIBUTOR

Dario Vincenzo Tarantini
RELATED COURSES

View all Courses

Keep Exploring