Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add data dynamically to an Array

Tags:

php

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? 
like image 213
sikas Avatar asked Jul 24 '10 12:07

sikas


People also ask

How do you add a value to an array dynamically?

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.

How do you add values to an array of objects?

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."

How do you add an element to an existing 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.


2 Answers

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.

like image 93
TimCinel Avatar answered Oct 01 '22 06:10

TimCinel


$array[] = 'Hi'; 

pushes on top of the array.

$array['Hi'] = 'FooBar'; 

sets a specific index.

like image 42
NikiC Avatar answered Oct 01 '22 06:10

NikiC