Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to last element of array

Tags:

arrays

php

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() );
like image 213
user1032531 Avatar asked Jun 02 '12 16:06

user1032531


People also ask

How do I add elements to the last array?

By using ArrayList as intermediate storage:Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.

How do I add elements to the end of an array in C++?

C++ arrays aren't extendable. You either need to make the original array larger and maintain the number of valid elements in a separate variable, or create a new (larger) array and copy the old contents, followed by the element(s) you want to add.

How do you add an element to an array?

First get the element to be inserted, say x. Then get the position at which this element is to be inserted, say pos. Then shift the array elements from this position to one position forward(towards right), and do this for all the other elements next to pos.


1 Answers

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.

like image 121
clentfort Avatar answered Nov 06 '22 05:11

clentfort