Search code examples
phparraysarray-map

How to write convert an anonymous functions to a regular function while using use $variable


I'm trying to figure out how to convert the array_map portion with the anonymous function to just a function while using the use function to be able to support php 5.2 but i keep getting an error. Here is my current code.

<?php

$collection = array();

$op_field = array(
    'fname' => 'sarmen',
    'lname' => 'b',
    'age' => 33,
    'gender' => 'male'
);

$nf_field = array(
    'type' => 'human',
    'age' => 30,
    'gender' => 'male',
    'ethnicity' => 'american'
);



array_map(function($op, $nf) use (&$collection)
{
    $collection[] = array(
        'op' => $op,
        'nf' => $nf
    );
}, $op_field, $nf_field);


print_r($collection);

I've tried

function mapping($op, $nf)
{
    $collection[] = array(
        'op' => $op,
        'nf' => $nf
    );
    return $collection;
}

array_map(mapping($op, $nf), use ($&collection), $op_field, $nf_field);

But that just gives a parse error. Any idea on how it would be written? I really appreciate it.


Solution

  • There's no need to pass in a reference to $collection, instead just do the following:

    function mapping($op, $nf)
    {
        return array(
            'op' => $op,
            'nf' => $nf
        );
    }
    
    $collection = array_map('mapping', $op_field, $nf_field);
    

    Yields:

    Array
    (
        [0] => Array
            (
                [op] => sarmen
                [nf] => human
            )
    
        [1] => Array
            (
                [op] => b
                [nf] => 30
            )
    
        [2] => Array
            (
                [op] => 33
                [nf] => male
            )
    
        [3] => Array
            (
                [op] => male
                [nf] => american
            )
    
    )
    

    Hope this helps :)