How to usethe += Operator in PHP

You can also use the += operator to append an associative array to the end of another associative array.

PHP
<?php

$person = ['fname' => 'Akash', 'lname' => 'Singh'];

// Add elements to the end of the array
$person += ['age' => 30, 'gender' => 'male'];

print_r($person);

?>

Output
Array
(
    [fname] => Akash
    [lname] => Singh
    [age] => 30
    [gender] => male
)

Explanation:

  • $person Array: An associative array containing information about a person.
  • += Operator: This operator is used to add the elements ‘age’ and ‘gender’ to the end of the $person array.

How to Add Elements to the End of an Array in PHP?

In PHP, arrays are versatile data structures that can hold multiple values. Often, you may need to add elements to the end of an array, whether it’s for building a list, appending data, or other purposes. PHP provides several ways to achieve this. In this article, we will explore different approaches to adding elements to the end of an array in PHP.

Table of Content

  • Using the array_push() Function
  • Using Square Brackets []
  • Using the += Operator

Similar Reads

Approach 1: Using the array_push() Function

The array_push() function is a built-in PHP function that allows you to add one or more elements to the end of an array....

Approach 2: Using Square Brackets []

In PHP, you can also add elements to the end of an array by using square brackets [] without specifying an index....

Approach 3: Using the += Operator

You can also use the += operator to append an associative array to the end of another associative array....