PHP Add Array Items

Add Array Item


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


Example
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = ["apple", "banana"];
$fruits[] = "orange"; // Add "orange" to the end of the array
print_r($fruits);
?>
</body>
</html>

Try it yourself

Associative Arrays


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


Example
<!DOCTYPE html>
<html>
<body>
<?php
$person = ["name" => "John", "age" => 30];
$person["gender"] = "male"; // Add a new key-value pair
print_r($person);
?>
</body>
</html>

Try it yourself

Add Multiple Array Items


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

Example
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = ["apple", "banana"];
array_push($fruits, "orange", "grape"); // Add multiple elements
print_r($fruits);
?>
</body>
</html>

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
<!DOCTYPE html>
<html>
<body>
<?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);
?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.