In this tutorial, you will learn how to remove or delete specific elements from php array by key, value, and index in PHP.
How to Delete Specific Elements from an Array By Key, Value and Index in PHP?
Here are some methods:
- Removing an array element by key
- Removing an array element by value
- Removing an array element by index
- Unset Multiple Keys from Array
Removing an array element by key
To remove an array element by key, you need to know the key of the element you want to remove.
Here’s an example:
<?php
$fruits = array("apple" => "red", "banana" => "yellow", "grape" => "purple");
unset($fruits["banana"]);
print_r($fruits);
?>
Removing an array element by value
To remove an array element by value, you need to search for the value and get its key. Then you can remove it from array by it’s value.
Here’s an example:
<?php
$fruits = array("apple", "papaya", "grape");
$key = array_search("papaya", $fruits);
if ($key !== false) {
unset($fruits[$key]);
}
print_r($fruits);
?>
Removing an array element by index
To remove an array element by index, you need to know the index of the element, which you want to remove.
Here’s an example:
<?php
$fruits = array("apple", "banana", "grape");
unset($fruits[1]);
print_r($fruits);
?>
Unset Multiple Keys from Array
Sometimes, you may need to remove multiple elements from an array. So, you can use a loop to iterate through the array and call unset()
on each key you want to remove.
Here’s an example:
$fruits = array(
"apple" => 0.50,
"banana" => 0.25,
"cherry" => 1.00,
"grape" => 0.75,
"orange" => 0.30
);
$keys_to_remove = array("banana", "orange");
foreach ($keys_to_remove as $key) {
if (array_key_exists($key, $fruits)) {
unset($fruits[$key]);
}
}
After running this code, the $fruits
the array will look like this:
Array ( [apple] => 0.5 [cherry] => 1 [grape] => 0.75 )
Conclusion
The unset()
a function is used to remove array elements by key, value, and index.
Recommended PHP Tutorials
- To Remove Elements or Values from Array PHP
- How to Convert String to Array in PHP
- Array Push and POP in PHP | PHP Tutorial
- PHP Search Multidimensional Array [key and value and return key]
- PHP Array to String Conversion – PHP Implode
- Array Functions In PHP
- Functions: Remove First Character From String PHP
- Remove Specific/Special Characters From String In PHP
- How to Replace First and Last Character From String PHP
- remove duplicates from multidimensional array PHP
- PHP Remove Duplicate Elements or Values from Array PHP
- PHP Convert Array to Comma Separated String
- Compare Arrays Keys and Values PHP
- PHP Object to Array Convert using JSON Decode
- Convert CSV to JSON PHP
- How to Check If the Variable is Empty in PHP