Open In App

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.

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.

<?php

$arr = [10, 20, 30, 40];

// Add elements to the end of the array
array_push($arr, 50, 60);

print_r($arr);

?>

Output
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
    [5] => 60
)

Explanation:

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.

<?php

$arr = [10, 20, 30, 40];

// Add elements to the
// end of the array
$arr[] = 50;
$arr[] = 60;

print_r($arr);

?>

Output
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
    [5] => 60
)

Explanation:

Approach 3: Using the += Operator

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:

Article Tags :