Deleting an element from an array in PHP?
Yes, there are multiple ways to delete an element from an array in PHP.
- Using the unset() function: The unset() function is used to remove a specific element from an array. Here's an example:
php$array = array('apple', 'banana', 'orange', 'grape');
unset($array[2]); // Remove the third element (orange) foreach ($array as $fruit) { echo $fruit . "\n"; // Output: apple banana grape }
- Using the array_splice() function: The array_splice() function can be used to remove a specific range of elements from an array. Here's an example:
php$array = array('apple', 'banana', 'orange', 'grape');
array_splice($array, 2, 1);
// Remove one element starting from the third element
foreach ($array as $fruit) {
echo $fruit . "\n";
// Output: apple banana grape
}
In both cases, the foreach loop will no longer include the element that was removed from the array.
Solution: 2
Deleting a single array element
If you want to delete just one array element you can use unset()
or alternatively \array_splice()
.
If you know the value and don’t know the key to delete the element you can use \array_search()
to get the key. This only works if the element does not occur more than once, since \array_search
returns the first hit only.
unset()
Note that when you use unset()
the array keys won’t change. If you want to reindex the keys you can use \array_values()
after unset()
, which will convert all keys to numerically enumerated keys starting from 0.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
// ↑ Key which you want to delete
Output:
[
[0] => a
[2] => c
]
Comments
Post a Comment