9

If I have the following array. What would be the best way to add a element to list[] for the last element of $myArray[]? Note that list[] has numerical indexes (i.e. not associative). Thanks!

$myArray[] = array( 'name' => 'hello', 'list' => array() );
1
  • 2
    Your question is a tad unclear. Could you post an example of what your result should look like? Commented Jun 2, 2012 at 16:07

5 Answers 5

8

If $myArray is not associative

array_push($myArray[count($myArray)-1]['list'], 'new element');

or

$myArray[count($myArray)-1]['list'][] = 'new element';

with this method you change the position of the array pointer.

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

2 Comments

Yes, this will likely work. Didn't know if there was a cleaner solution using end()
when you use end you get a copy of the last value, not a reference. So if you change the value it does not effect the array. If you use end you have to call it at first, then use key to get the key of the last element and can then modify the array. If $myArray is not associative you might want to do that.
5

You can do it like this:

$last = array_pop($myArray); // remove last element of array
$last['list'][] = "new element"; // add element to array
$myArray[] = $last; // add changed last element again

Comments

2
$myArray[count($myArray)-1]['list'][]="something to go in 'list' array";//this shall append 
//to the second dimension array with keyname 'list'

2 Comments

Instead of $myArray[0], it would need to point to the last element of $myArray, not 0.
Gotcha. Same solution as clenfort. Thanks!
1

There is actually a more beautiful way (in my opinion):

$ref = &$myArray[];
$ref['list'][] = 'new item'

As you can see $ref - is reference to the last element of $myArray, so you can change the last element by changing $ref;

Comments

-3

array_push function do that.

array_push()

1 Comment

After the PHP manual this has the same effect as $array[] = $var; which he has used in his code already. So I don't think he's searching for this.

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.