I want to add data to an array dynamically. How can I do that? Example
$arr1 = [ 'aaa', 'bbb', 'ccc', ]; // How can I now add another value? $arr2 = [ 'A' => 'aaa', 'B' => 'bbb', 'C' => 'ccc', ]; // How can I now add a D?
Since the size of an array is fixed you cannot add elements to it dynamically. But, if you still want to do it then, Convert the array to ArrayList object. Add the required element to the array list.
The push() function is a built-in array method of JavaScript. It is used to add the objects or elements in the array. This method adds the elements at the end of the array. "Note that any number of elements can be added using the push() method in an 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.
There are quite a few ways to work with dynamic arrays in PHP. Initialise an array:
$array = array();
Add to an array:
$array[] = "item"; // for your $arr1 $array[$key] = "item"; // for your $arr2 array_push($array, "item", "another item");
Remove from an array:
$item = array_pop($array); $item = array_shift($array); unset($array[$key]);
There are plenty more ways, these are just some examples.
$array[] = 'Hi';
pushes on top of the array.
$array['Hi'] = 'FooBar';
sets a specific index.
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