Foreach and Array_walk in PHP

How to use the PHP Foreach loop construct to iterate over arrays.

1921 views
d

By. Jacob

Edited: 2021-02-21 15:02

PHP tutorial

In PHP we have the foreach loop which is a developer-friendly loop construct that allows to iterate over arrays and objects.

The advantage of using a foreach loop instead of a while or for is that it is easier to use, since the array iteration happens automatically, without the need to think about counters or missing array keys.

$some_array = array('Apple', 'Banana', 'Orange', 'Carrot', 'Spinach');

foreach ($some_array as $key => $value) {
    echo PHP_EOL . $key . ':' . $value;
}

Output:

0:Apple
1:Banana
2:Orange
3:Carrot
4:Spinach

As an alternative to foreach, you could also use array_walk with an anonymous function:

array_walk($some_array, function ($value, $key) {
    echo PHP_EOL . $key . ':' . $value;
});

Using foreach with objects

The foreach loop works exactly the same way when using it to iterate over objects. When using objects, the object properties will take the place of "keys". It works well while strings and integers are used as values, but arrays and nested objects will need special treatment.

Here is an example of how to iterate over an object in PHP:

$containerObject = new stdClass();
$containerObject->one = 1;
$containerObject->two = 2;

foreach ($containerObject as $property_name => $value) {
  echo $property_name .' '. $value . PHP_EOL;
}
exit();

The advantage of using objects instead of arrays for data storage is that objects are simply more powerful. You may even create your own class instead of the generaic stdClass.

The stdClass is just a generic empty class in PHP, it is useful for quick storage of data, but not so much for more advanced stuff.

If you are not sure what type the properties contain, you can use the "is_*" functions, here is an example using the is_string function:

foreach ($containerObject as $property_name => $value) {
  if (!is_string($property_name)) {
    break;
  }
  echo $property_name .' '. $value . PHP_EOL;
}

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials