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
$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