[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);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait 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 fn ($value) => $value.$value, $array); // with an arrow function as of PHP 7.4

        // the old way before PHP 7.4
        // $array1 = array_map(static function ($value): string {
        //    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  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  Run on 3v4l.org

  Work with me!

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet50Trait
 */
final class Snippet50Test extends KernelTestCase
{
    /**
     * @see Snippet50Trait::snippet50
     */
    public function testSnippet50(): void
    {
        $array = [
            'kikoo' => 'cat',
            'foo' => 'bar',
        ];

        $array1 = array_map(static function ($value): string {
            return $value.$value;
        }, $array);

        self::assertSame([
            'kikoo' => 'catcat',
            'foo' => 'barbar',
        ], $array1);

        $array2 = array_map('strtoupper', $array);
        self::assertSame([
            'kikoo' => 'CAT',
            'foo' => 'BAR',
        ], $array2);
    }
}