PHP: How to remove specific element from an array?
Use array_search
to get the key and remove it with unset
if found:
if (($key = array_search('strawberry', $array)) !== false) {
unset($array[$key]);
}
array_search
returns false (null until PHP 4.2.0) if no item has been found.
And if there can be multiple items with the same value, you can use array_keys
to get the keys to all items:
foreach (array_keys($array, 'strawberry') as $key) {
unset($array[$key]);
}
Deleting an element from an array in PHP
There are different ways to delete an array element, where some are more useful for some specific tasks than others.
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
]
\array_splice()
method
If you use \array_splice()
the keys will automatically be reindexed, but the associative keys won’t change — as opposed to \array_values()
, which will convert all keys to numerical keys.
\array_splice()
needs the offset, not the key, as the second parameter.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
// ↑ Offset which you want to delete
Output:
[
[0] => a
[1] => c
]
array_splice()
, same as unset()
, take the array by reference. You don’t assign the return values of those functions back to the array.
Deleting multiple array elements
If you want to delete multiple array elements and don’t want to call unset()
or \array_splice()
multiple times you can use the functions \array_diff()
or \array_diff_key()
depending on whether you know the values or the keys of the elements which you want to delete.
\array_diff()
method
If you know the values of the array elements which you want to delete, then you can use \array_diff()
. As before with unset()
it won’t change the keys of the array.
Code:
$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = \array_diff($array, ["a", "c"]);
// └────────┘
// Array values which you want to delete
Output:
[
[1] => b
]
\array_diff_key()
method
If you know the keys of the elements which you want to delete, then you want to use \array_diff_key()
. You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
// ↑ ↑
// Array keys which you want to delete
Output:
[
[1] => b
]
If you want to use unset()
or \array_splice()
to delete multiple elements with the same value you can use \array_keys()
to get all the keys for a specific value and then delete all elements.
\array_filter()
method
If you want to delete all elements with a specific value in the array you can use \array_filter()
.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_filter($array, static function ($element) {
return $element !== "b";
// ↑
// Array value which you want to delete
});
Output:
[
[0] => a
[1] => c
]
PHP remove specific item from array
With array_search
you can get the first matching key of the given value, then you can delete it with unset
.
if (false !== $key = array_search(401, $array)) {
unset($array[$key]);
}
PHP array delete by value (not key)
Using array_search()
and unset
, try the following:
if (($key = array_search($del_val, $messages)) !== false) {
unset($messages[$key]);
}
array_search()
returns the key of the element it finds, which can be used to remove that element from the original array using unset()
. It will return FALSE
on failure, however it can return a false-y value on success (your key may be 0
for example), which is why the strict comparison !==
operator is used.
The if()
statement will check whether array_search()
returned a value, and will only perform an action if it did.
Remove a element from an array and assign to a variable
You can copy the array to $cars_without_volvo
and unset from that, then you'd have two different arrays. unset()
doesn't return anything, it's used to unset elements or variables directly.
This of course assumes that Volvo
is always the first element in the $cars
array, because we unset the first element.
$cars = array("Volvo", "BMW", "Toyota");
$cars_without_volvo = $cars;
unset($cars_without_volvo[0]);
print_r($cars);
print_r($cars_without_volvo);
Outputs
Array (
[0] => Volvo
[1] => BMW
[2] => Toyota
)
Array (
[1] => BMW
[2] => Toyota
)
You can also find the key for the Volvo
element dynamically, by using array_search()
(demo), by replacing the unset()
line above with the one below.
unset($cars_without_volvo[array_search("Volvo", $cars_without_volvo)]);
Using array_shift()
as shown in the other answer is most likely the better approach - if the element you wish to remove is the first one. If you want to remove elements in a difference index than the first or last, using this approach might be easier.
- PHP.net on
unset()
- Live demo
How to remove a single element from a PHP session array?
The easiest way is to get the value, remove the item, and set the session variable again.
$data = $_SESSION['array']; // Get the value
unset($data[1]); // Remove an item (hardcoded the second here)
$_SESSION['array'] = $data; // Set the session value with the new array
Update:
Or like @Qirel said, you can unset the item directly if you know the number.
unset($_SESSION['array'][1]);
Update 2
If you want to remove the element by its value, you can use array_search
to find the key of this element. Note that if there are to elements with this value, only the first will be removed.
$value_to_delete = '13/02/2017';
if (($key = array_search($value_to_delete, $_SESSION['array'])) !== false)
unset($_SESSION['array'][$key]);
How to remove an element in array containing a certain word in PHP
Arrays have keys and values. You're looking at the values, but trying to unset keys. Unless they match (i.e. your array looks like ['test' => 'test', 'freedom' => 'freedom']
), this isn't what you want. Try this:
foreach ($myarray as $key => $value){
// remove words containing 'free'
if (strpos($value, 'free') !== false) {
unset($myarray[$key]);
}
}
Related Topics
$_Server['Http_Referer'] Missing
Parsing Json Object in PHP Using Json_Decode
PHP Replacing Multiple Spaces With a Single Space
Does PHP Time() Return a Gmt/Utc Timestamp
PHP Library For Parsing Xml With a Colons in Tag Names
Codeigniter: Create New Helper
How to Set Proper Codeigniter Base Url
PHP Equivalent of .Net/Java'S Tostring()
How to Get Code Point Number For a Given Character in a Utf-8 String
Send Value of Submit Button When Form Gets Posted
What Are Register_Globals in PHP
Best Practice on PHP Singleton Classes
Laravel View Not Found Exception
: Operator (The 'Elvis Operator') in PHP
PHP: Recreate and Display an Image from Binary Data