Open In App

How to add and remove Elements from Array in PHP?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Adding and removing elements from arrays in PHP can be achieved using various built-in functions and array manipulation techniques.

Adding Elements to an Array:

Using [ ] Syntax:

You can add elements to an array by assigning values to new or existing keys using square brackets [ ].

$array = []; // Initialize an empty array
$array[] = "element1"; // Add "element1" to the end of the array
$array[] = "element2"; // Add "element2" to the end of the array

Using array_push( ) Function:

PHP array_push() appends one or more elements to the end of an array.

$array = [ ]; // Initialize an empty array
array_push($array, "element1", "element2");

// Add "element1" and "element2" to the end of the array

Ref: https://www.geeksforgeeks.org/how-to-insert-a-new-element-in-an-array-in-php/

Removing Elements from an Array

Using unset() Function:

PHP unset() removes a specified element from an array.

$array = ["element1", "element2", "element3"]; 
// Initialize an array
unset($array[1]);
// Remove the element at index 1 ("element2")

Using array_pop() Function:

PHP array_pop() removes and returns the last element of an array.

$array = ["element1", "element2", "element3"]; // Initialize an array
$lastElement = array_pop($array);
// Remove and return the last element ("element3")

Using array_shift() Function:

PHP array_shift() removes and returns the first element of an array, shifting all other elements to a lower index.

$array = ["element1", "element2", "element3"]; 
// Initialize an array
$firstElement = array_shift($array);
// Remove and return the first element ("element1")

Ref: https://www.geeksforgeeks.org/how-to-delete-an-element-from-an-array-in-php/


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads