jam3
jam3

Reputation: 21

changing data in array

I would like to add fruits/ to the beginning of all of the values in an array.

How can I do this?

For example - array before:

Array 
( 
    [0] => Array 
    ( 
        [fruits] => apple/mango
    ) 
    [1] => Array 
    ( 
        [fruits] => orange/strawberries
    ) 
    [2] => Array 
    ( 
        [fruits] => orange/strawberries
    ) 
)

Array after:

Array 
( 
    [0] => Array 
    ( 
        [fruits] => fruits/apple/mango
    ) 
    [1] => Array 
    ( 
        [fruits] => fruits/orange/strawberries
    ) 
    [2] => Array 
    ( 
        [fruits] => fruits/orange/strawberries
    ) 
)

Is the solution the .= operator?

Upvotes: 2

Views: 81

Answers (1)

Jon
Jon

Reputation: 437336

Using array_map and an anonymous function (requires PHP >= 5.3):

$array = array_map(function($item) {
                       return array('fruits' => 'fruits/'.reset($item));
                   }, $array);

It's slightly harder than it could be, since your input array is of the form

$array = array(
    array('fruits' => 'apple/mango'),
    array('fruits' => 'orange/strawberries'),
);

while it seems it could also have been

$array = array(
    'apple/mango',
    'orange/strawberries',
);

You can do the same in a slightly more cumbersome way for PHP < 5.3 -- if you need this, please leave a comment.

Upvotes: 3

Related Questions