Advertisement

Google Ad Slot: content-top

PHP Add Array Items

~1 min read · PHP
On this page

Add Array Item


You can add elements to the end of an array using the [] operator.

Example
Try it yourself

Associative Arrays


To add items to an associative array, use brackets [] and assigning a value to a new key.

Example
"John", "age" => 30]; $person["gender"] = "male"; // Add a new key-value pair print_r($person); ?>
Try it yourself

Add Multiple Array Items


array_push() function appends one or more elements to the end of an array.

Example
Try it yourself

Add Multiple Items to Associative Arrays


You can use the += operator to add multiple key-value pairs to an associative array in PHP.

Example
"John", "age" => 30]; $newData = [ "gender" => "male", "country" => "USA", "age" => 35 // This key already exists in the original array and will not be updated ]; $person += $newData; // Add the new data print_r($person); ?>
Try it yourself