Question

I have a quite simple question, yet I cannot get a way around it. I'd like to walk through an array and change it's items with a function, then return a new array of the new values.

Here is my array:

$array = array('thing1', 'thing2', 'thing3');

This is my function:

function testing ($string, $to)
{
    retrun substr($string, 0, $to);
}

And I'd like to do the following:

array_map(testing($string, 2), $array);

The above statement is not working properly. Can anyone tell me how to make this array_map function to work as expected?

Was it helpful?

Solution

Pass array_map an anonymous function that calls testing.

array_map(function($string){
    return testing($string, 2);
}, $array);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top