46

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?
6

10 Answers 10

106

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, and these are just some examples.

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

3 Comments

I just want to add something. array_push function should only be used for big arrays as described in the description. Always prefer $array[] = "new item" for small insertions. php.net/manual/en/function.array-push.php
just to add to your very good answer, $array = []; is also an option for array initialisation
Why are "$arr1" and "$arr2" only in the comments? Why aren't they in the code?
13
$array[] = 'Hi';

pushes on top of the array.

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

sets a specific index.

1 Comment

The two arrays in the question contain two different kinds of data. At least some part of the answer ought to be more specific.
10

Let's say you have defined an empty array:

$myArr = array();

If you want to simply add an element, e.g., 'New Element to Array', write

$myArr[] = 'New Element to Array';

If you are calling the data from the database, the below code will work fine

$sql = "SELECT $element FROM $table";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0) // If it finds any row
{
    while($result = mysql_fetch_object($query))
    {
        // Adding data to the array
        $myArr[] = $result->$element;
    }
}

1 Comment

From where do you see $element and $table values are SELECTed ?
6

You should use method array_push to add a value or an array to an existing array:

$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

/** GENERATED OUTPUT
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
*/

Comments

5

Like this:

$array[] = 'newItem';

Comments

3

In additon to directly accessing the array, there is also

array_push — Push one or more elements onto the end of array

Comments

2
$dynamicarray = array();

for($i=0; $i<10; $i++)
{
    $dynamicarray[$i] = $i;
}

1 Comment

Please include an explanation with your answer.
0

Adding array elements dynamically to an Array And adding new element to an Array

$samplearr=array();
$count = 0;
foreach ($rslt as $row) {
        $arr['feeds'][$count]['feed_id'] = $row->feed_id;
        $arr['feeds'][$count]['feed_title'] = $row->feed_title;
        $arr['feeds'][$count]['feed_url'] = $row->feed_url;
        $arr['feeds'][$count]['cat_name'] = $this->get_catlist_details($row->feed_id);
        foreach ($newelt as $cat) {
            array_push($samplearr, $cat);              
        }
        ++$count;
}
$arr['categories'] = array_unique($samplearr); //,SORT_STRING

$response = array("status"=>"success","response"=>"Categories exists","result"=>$arr);

Comments

0

just for fun...

$array_a = array('0'=>'foo', '1'=>'bar');
$array_b = array('foo'=>'0', 'bar'=>'1');

$array_c = array_merge($array_a,$array_b);

$i = 0; $j = 0;
foreach ($array_c as $key => $value) {
    if (is_numeric($key)) {$array_d[$i] = $value; $i++;}
    if (is_numeric($value)) {$array_e[$j] = $key; $j++;}
}

print_r($array_d);
print_r($array_e);

2 Comments

An explanation would be in order.
OK, the OP has left the building: "Last seen more than 9 years ago". Perhaps somebody else can chime in?
0

The fastest way, I think:

$newArray = array();

for($count == 0; $row = mysql_fetch_assoc($getResults); $count++)
{
    foreach($row as $key => $value)
    {
        $newArray[$count]{$key} = $row[$key];
    }
}

Comments

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.