2

Here's my array

$myArr  = array(array('one', 'two'), array('one', 'two'));

I would like add an element to every array inside the $myArr. I dont wanna loop over each array inside and add that element. Is there any quicker way to achieve this using array_map or array_walk.. preferably with one line of code?

Result array should be like

$myArr  = array(array('one', 'two','three'), array('one', 'two','three'));

Thanks a bunch

Got it, Kudos to @strager

$myvar = 'Three';

$myArr = array_map(function ($subarray) {  global $myvar; $subarray[] = $myvar;   return $subarray;}, $myArr);

2 Answers 2

2

With array_walk:

array_walk($myArr, create_function('&$subarray', '$subarray[] = "three";'));

With array_map:

$myArr = array_map(create_function('$subarray', '$subarray[] = "three"; return $subarray;'), $myArr);

With anonymous functions an array_map (untested; I don't have access to PHP5.3):

$myArr = array_map(function ($subarray) {
    $subarray[] = "three";
    return $subarray;
}, $myArr);

Or of course, the better solution (for PHP < 5.3):

function pushToEndOfSubarrays($array, $item) {
    $ret = array();

    foreach ($array as $key => $subarray) {
        $subarray[] = $item;
        $ret[$key] = $subarray;
    }

    return $ret;
}

$myArr = pushToEndOfSubarrays($myArr, 'three');
Sign up to request clarification or add additional context in comments.

2 Comments

I'm using : array_walk($myArr, create_function('&$subarray', '$subarray[] = "three";')); How can i pass my element varible to add into create_function? Its a dynamic value rather than text like 'three'
@Naresh, That's where things get tricky. Just use one of the last two suggestions in my answer.
2

you can use function array_push() for push array into array

int array_push ( array &$array , mixed $var [, mixed $... ] );

This may help you as your requirements.

thanks.

3 Comments

Wouldn't one still require a loop for this? otherwise it would simply append the value to the end of the parent array and not the children.
The questioner wants to push one element to each array inside $myArr. They don't seem to want to push a new array to $myArr.
Thanks for the reply but i just want to add an element to all arrays inside my main array.. not pushing an element into array

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.