I am Learn.i.ng

How to efficiently loop through PHP array elements

Posted:    Updated:   by Afolabi

Use case: you have an array of images to which you want to prepend a path to get the full URL to be sent as an API response.


$images = array("image1.png", "image2.png", "image3.png", "image4.png", "image5.png");

A traditional way of doing things will be looping through each element of the array, prepending the path to each element, pushing the modified element to another array and returning that array. Like so:


$image_urls = array();
foreach( $images AS $image ) :
  $image = "https://example.com/images/{$image}";
  array_push($image_urls, $image);
endforeach;
print_r($image_urls);

An efficient way of doing the same thing is:


array_walk($images, function(&$value, $key) {
  $value = "https://example.com/images/{$value}";
});

array_walk — Apply a user supplied function to every member of an array – PHP array_walk() documentation

The first argument you have to pass to array_walk is the array you want to perform your operation on; then you specify a callback function. In the example above, I used a closure. You would notice that in the closure’s parameter, I typed &$value instead of just $value. This is because I want to modify the current element the array pointer is on. In this case, we are changing the elements from just being the file name to being full URLs.

array_walk() returns true on successful execution. Now, if we type:


print_r($images);

Our $images array will return this:


Array
(
    [0] => https://example.com/images/image1.png
    [1] => https://example.com/images/image2.png
    [2] => https://example.com/images/image3.png
    [3] => https://example.com/images/image4.png
    [4] => https://example.com/images/image5.png
)

Notice that we did not have to create another array, push to it or return any value; neat! Right?

Going a step further

What if you want to use the same callback function in different places?

How would you use array_walk within a class?


class Images {
  private function prependPath(&$value, $key, string $prefix) {
    $value = $prefix . $value;
  }

  public function getImageUrls(array $images) {
    array_walk($images, array($this, 'prependPath'), "https://example.com/images/");
    return $images;
  }
}

prependPath() can now be used multiple times within the class passing the prefix you want to $prefix
Note: instead of passing prependPath() directly as the second argument of array_walk(), an array is used instead. The first item in the array — $this — means the method to call is within this same class or its parent. That is how to use a method with array_walk() within a class.

Resources

Do you know why we did not return array_walk($images, array($this, 'prependPath'));?

Leave a Reply