Current Location: Home> Latest Articles> How to Add and Remove Array Elements in PHP

How to Add and Remove Array Elements in PHP

M66 2025-06-21

How to Add and Remove Array Elements in PHP

In PHP, arrays are a common and essential data structure that can store multiple values and support dynamically adding or removing elements. This article will explain how to add and remove array elements in PHP with related code examples.

1. Adding Elements

  1. Using Bracket [] Syntax

The simplest way to add elements is by using the bracket [] syntax. Here's an example:

$arr = ["apple", "banana", "orange"];
$arr[] = "grape";
print_r($arr);

This code will add a new element "grape" to the array $arr. The output is as follows:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)
  1. Using the array_push() Function

PHP also provides the array_push() function, which allows adding one or more elements to the end of an array. Here's an example:

$arr = ["apple", "banana", "orange"];
array_push($arr, "grape", "watermelon");
print_r($arr);

This code will add two elements, "grape" and "watermelon", to the array $arr. The output is as follows:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
    [4] => watermelon
)

2. Removing Elements

  1. Using the unset() Function

The unset() function can be used to remove one or more elements from an array. Here's an example:

$arr = ["apple", "banana", "orange"];
unset($arr[1]);
print_r($arr);

This code will remove the element "banana" at index 1 in the array $arr. The output is as follows:

Array
(
    [0] => apple
    [2] => orange
)
  1. Using the array_splice() Function

The array_splice() function allows more complex array operations, including deleting, replacing, or inserting elements. Here's an example:

$arr = ["apple", "banana", "orange"];
array_splice($arr, 1, 1);
print_r($arr);

This code will remove the element "banana" at index 1 in the array $arr. The output is as follows:

Array
(
    [0] => apple
    [1] => orange
)
  1. Using the array_pop() Function

The array_pop() function can be used to remove the last element of an array. Here's an example:

$arr = ["apple", "banana", "orange"];
array_pop($arr);
print_r($arr);

This code will remove the last element, "orange", from the array $arr. The output is as follows:

Array
(
    [0] => apple
    [1] => banana
)

Conclusion

This article introduced various methods for adding and removing elements from PHP arrays, with code examples provided. These methods allow you to easily manipulate PHP arrays and dynamically add or remove elements as needed.

Whether you're using bracket [] syntax, array_push(), unset(), array_splice(), or array_pop(), these functions provide flexible and efficient ways to manage array elements in PHP, enhancing your development process.

We hope this article helps you better understand how to add and remove elements from PHP arrays.