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() );
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With