Table of Contents
Overview:
In PHP, arrays are used to store multiple values in a single variable. Sometimes, you may need to remove a specific element from an array based on its value or key. In this tutorial, we will show you how to remove a specific element from an array in PHP.
There are different ways to remove an element from an array in PHP, but the most common ones are using the unset()
function or using the array_splice()
function.
Method 1: Using unset() Function
The unset()
function removes a specific element from an array based on its key. Here’s the syntax of the unset()
function:
unset($array[key]);
Where $array
is the name of the array and key
is the key of the element you want to remove.
Here’s an example:
// Define an array
$fruits = array("apple", "banana", "orange", "grape");
// Remove the element with value "orange"
$key = array_search("orange", $fruits);
unset($fruits[$key]);
// Output the updated array
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
[3] => grape
)
In this example, we defined an array $fruits
with four elements. We then used the array_search()
function to find the key of the element with the value "orange"
. Finally, we used the unset()
function to remove the element with that key, and output the updated array.
Method 2: Using array_splice() Function
The array_splice()
function removes a specific range of elements from an array and replaces them with new elements. Here’s the syntax of the array_splice()
function:
array_splice($array, $offset, $length, $replacement);
Where $array
is the name of the array, $offset
is the starting index of the range to be removed, $length
is the number of elements to be removed, and $replacement
is an optional array of elements to replace the removed elements.
Here’s an example:
// Define an array
$fruits = array("apple", "banana", "orange", "grape");
// Remove the element with value "orange"
$key = array_search("orange", $fruits);
array_splice($fruits, $key, 1);
// Output the updated array
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
[3] => grape
)
In this example, we used the array_search()
function to find the key of the element with the value "orange"
. We then used the array_splice()
function to remove one element starting from that key, and output the updated array.
That’s it! You now know how to remove a specific element from an array in PHP using the unset()
function or the array_splice()
function.