2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.