Open In App

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

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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
<?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:

  • $arr Array: An array containing some fruit names.
  • array_push(): This function takes the array and the elements to be added as arguments. Here, ‘grape’ and ‘mango’ are added to the end of the $fruits 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.

PHP
<?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:

  • $arr Array: An array containing some numbers.
  • Square Brackets []: By using [], we add the numbers 4 and 5 to the end of the $numbers array.

Approach 3: Using the += Operator

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.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads