[PHP] Modifying array values with array_map and an anonymous function

Published on 2019-11-03 • Modified on 2019-11-03

This is how to modify all values of a PHP array with an anonymous function (closure). Note that when using array_map, the closure doesn't "know" the key of the element it is processing. If you need to get the key, use array_walk.


<?php declare(strict_types=1);

// src/Controller/Snippet/Snippet50Trait.php

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait in order to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet50Trait
{
    public function snippet50(): void
    {
        $array = [
            'kikoo' => 'cat',
            'foo' => 'bar',
        ];
        $array1 = array_map(static function ($value) {
            return $value.$value;
        }, $array);

        // for simple cases, pass the PHP function name directly
        $array2 = array_map('strtoupper', $array);

        print_r($array1);
        print_r($array2);

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Run on 3v4l.org