Advertisement
Google Ad Slot: content-top
PHP Add Array Items
Add Array Item
You can add elements to the end of an array using the [] operator.
Example
<?php
$fruits = ["apple", "banana"];
$fruits[] = "orange"; // Add "orange" to the end of the array
print_r($fruits);
?>
Associative Arrays
To add items to an associative array, use brackets [] and assigning a value to a new key.
Example
<?php
$person = ["name" => "John", "age" => 30];
$person["gender"] = "male"; // Add a new key-value pair
print_r($person);
?>
Add Multiple Array Items
array_push() function appends one or more elements to the end of an array.
Example
<?php
$fruits = ["apple", "banana"];
array_push($fruits, "orange", "grape"); // Add multiple elements
print_r($fruits);
?>
Add Multiple Items to Associative Arrays
You can use the += operator to add multiple key-value pairs to an associative array in PHP.
Example
<?php
$person = ["name" => "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);
?>