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: 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]);
}
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.
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]);
}
}
PHP Array Delete Element or Subtract
Loop the array and subtract and/or unset values accordingly.
$arr = [20,40,30,50];
$var =30;
Foreach($arr as $key => &$val){
If($var > $val){
$var -= $val;
Unset($arr[$key]);
}Else{
$val -= $var;
$var = 0;
}
}
Unset($val);
Var_dump($arr);
https://3v4l.org/vJN2o
You can add this line If($var>0) Echo $var;
too see if there is anything remaing in the $var when the loop ends.
https://3v4l.org/LU2Tf
Updated links to include $var =0;
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 - Remove and return an element from an associative array
Looking quickly at the official PHP documentation, in the current version (7.2) doesn't have a function that removes and returns an element by the key.
But as you mentioned there are several ways to solve this problem. As you can see at: https://stackoverflow.com/a/10898827/4214312
How to delete previous all elements from a specified index in PHP?
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$output = array_slice($array, 3);
output:
array(2) {
[0]=> string(1) "d"
[1]=> string(1) "e"
}
Another solution with saving index
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$output = array_slice($array, 3, null, true);
output:
array(2) {
[3]=> string(1) "d"
[4]=> string(1) "e"
}
https://www.php.net/manual/en/function.array-slice.php
Related Topics
Php 7 With Phpmyadmin Gives Lots of Deprecation Notices
Sending Message in Telegram Bot With Images
Reading Numbers as Text Format With Phpexcel
Regex to Check the String Contains Only Letter and Numbers But Not Only Numbers
How to Get Newest Data With 'Created_At' Column
How to Pass a PHP Variable Using the Url
Comparing Date from Variable to MySQL Date
Selected Value Get from Db into Dropdown Select Box Option Using PHP MySQL Error
Laravel Eloquent Sum of Multiplied Columns
Setting Selected Option in Laravel Form
Encoding CSV File With Arabic Content
How to Convert Jquery Ajax Success Data to a PHP Variable
How to Properly Encode Utf-8 for JavaScript and Json
Mysql Combine Two Columns into One in Query
How to Get Max and Min Value in a Multidimensional Array
Using Maatwebsite Excel 3.1 Export How to Set Background Color for Cells and Font Size for Heading