How to add and remove Elements from Array in PHP?
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
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")