PHP Add Array Items

To add items to an array in PHP, you can use several methods depending on the type of array (indexed or associative). Here are the common ways:

1. Add to Indexed Array

$fruits = ["apple", "banana"]; $fruits[] = "orange"; // Add at the end array_push($fruits, "grape", "melon"); // Add multiple items print_r($fruits);

2. Add to Associative Array

$user = [ "name" => "John", "age" => 30 ]; $user["email"] = "john@example.com"; // Add new key-value pair print_r($user);

3. Merge Arrays

$a = [1, 2]; $b = [3, 4]; $c = array_merge($a, $b); // Combine arrays print_r($c);

4. Using the + Operator (Preserves Keys)

$a = ["a" => 1]; $b = ["b" => 2]; $c = $a + $b; // $a values take precedence if keys overlap print_r($c);