I have a PHP array as follows:
$messages = [312, 401, 1599, 3, ...];
I want to delete the element containing the value $del_val
(for example, $del_val=401
), but I don't know its key. This might help: each value can only be there once.
I'm looking for the simplest function to perform this task, please.
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.
Well, deleting an element from array is basically just set difference with one element.
array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3]
It generalizes nicely, you can remove as many elements as you like at the same time, if you want.
Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. Pick the one you need.
[$element]
, I used array($element)
instead. No biggie, but just wanted anyone who had a similar issue to know that they weren't alone
array_diff
uses (string) $elem1 === (string) $elem2
as its equality condition, not $elem1 === $elem2
as you might expect. The issue pointed out by @nischayn22 is a consequence of this. If you want something to use as a utility function that will work for arrays of arbitrary elements (which might be objects), Bojangle's answer might be better for this reason.
array_diff()
and thus nudges the runtime up to O(n lg n) from O(n).
One interesting way is by using array_keys()
:
foreach (array_keys($messages, 401, true) as $key) {
unset($messages[$key]);
}
The array_keys()
function takes two additional parameters to return only keys for a particular value and whether strict checking is required (i.e. using === for comparison).
This can also remove multiple array items with the same value (e.g. [1, 2, 3, 3, 4]
).
array_values()
as well; the remaining keys are still in the same order though, so technically it's not "unsorted"
array_keys()
could do a search.
If you know for definite that your array will contain only one element with that value, you can do
$key = array_search($del_val, $array);
if (false !== $key) {
unset($array[$key]);
}
If, however, your value might occur more than once in your array, you could do this
$array = array_filter($array, function($e) use ($del_val) {
return ($e !== $del_val);
});
Note: The second option only works for PHP5.3+ with Closures
$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);
The Best way is array_splice
array_splice($array, array_search(58, $array ), 1);
Reason for Best is here at http://www.programmerinterview.com/index.php/php-questions/how-to-delete-an-element-from-an-array-in-php/
[1, 2, 4 => 3]
.
3
, the array will be [1, 2, 3]
; in other words, the value wasn't removed. To be clear, I'm not saying it fails in all scenarios, just this one.
Or simply, manual way:
foreach ($array as $key => $value){
if ($value == $target_value) {
unset($array[$key]);
}
}
This is the safest of them because you have full control on your array
array_splice()
instead of unset()
will reorder the array indexes too, which could be better in this case.
With PHP 7.4 using arrow functions:
$messages = array_filter($messages, fn ($m) => $m != $del_val);
To keep it a non-associative array wrap it with array_values()
:
$messages = array_values(array_filter($messages, fn ($m) => $m != $del_val));
foreach()
loop, but this is much more concise.
function array_remove_by_value($array, $value)
{
return array_values(array_diff($array, array($value)));
}
$array = array(312, 401, 1599, 3);
$newarray = array_remove_by_value($array, 401);
print_r($newarray);
Output
Array ( [0] => 312 [1] => 1599 [2] => 3 )
you can do:
unset($messages[array_flip($messages)['401']]);
Explanation: Delete the element that has the key 401
after flipping the array.
401
?
To delete multiple values try this one:
while (($key = array_search($del_val, $messages)) !== false)
{
unset($messages[$key]);
}
The accepted answer converts the array to associative array, so, if you would like to keep it as a non-associative array with the accepted answer, you may have to use array_values
too.
if(($key = array_search($del_val, $messages)) !== false) {
unset($messages[$key]);
$arr = array_values($messages);
}
The reference is here
If you don't know its key it means it doesn't matter.
You could place the value as the key, it means it will instantly find the value. Better than using searching in all elements over and over again.
$messages=array();
$messages[312] = 312;
$messages[401] = 401;
$messages[1599] = 1599;
$messages[3] = 3;
unset($messages[3]); // no search needed
PHP 7.4 or above
function delArrValues(array $arr, array $remove) {
return array_filter($arr, fn($e) => !in_array($e, $remove));
};
So, if you have the array as
$messages = [312, 401, 1599, 3];
and you want to remove both 3, 312
from the $messages array, You'd do this
delArrValues($messages, [3, 312])
It would return
[401, 1599]
The best part is that you can filter multiple values easily, even there are multiple occurrences of the same value.
array_filter
version could be used on older versions of php, such as: ` array_filter( $arr, function($arg) use ($black_list) { return !in_array($arg, $black_list); } ); `
Borrowed the logic of underscore.JS _.reject and created two functions (people prefer functions!!)
array_reject_value: This function is simply rejecting the value specified (also works for PHP4,5,7)
function array_reject_value(array &$arrayToFilter, $deleteValue) {
$filteredArray = array();
foreach ($arrayToFilter as $key => $value) {
if ($value !== $deleteValue) {
$filteredArray[] = $value;
}
}
return $filteredArray;
}
array_reject: This function is simply rejecting the callable method (works for PHP >=5.3)
function array_reject(array &$arrayToFilter, callable $rejectCallback) {
$filteredArray = array();
foreach ($arrayToFilter as $key => $value) {
if (!$rejectCallback($value, $key)) {
$filteredArray[] = $value;
}
}
return $filteredArray;
}
So in our current example we can use the above functions as follows:
$messages = [312, 401, 1599, 3, 6];
$messages = array_reject_value($messages, 401);
or even better: (as this give us a better syntax to use like the array_filter one)
$messages = [312, 401, 1599, 3, 6];
$messages = array_reject($messages, function ($value) {
return $value === 401;
});
The above can be used for more complicated stuff like let's say we would like to remove all the values that are greater or equal to 401 we could simply do this:
$messages = [312, 401, 1599, 3, 6];
$greaterOrEqualThan = 401;
$messages = array_reject($messages, function ($value) use $greaterOrEqualThan {
return $value >= $greaterOrEqualThan;
});
I know this is not efficient at all but is simple, intuitive and easy to read. So if someone is looking for a not so fancy solution which can be extended to work with more values, or more specific conditions .. here is a simple code:
$result = array();
$del_value = 401;
//$del_values = array(... all the values you don`t wont);
foreach($arr as $key =>$value){
if ($value !== $del_value){
$result[$key] = $value;
}
//if(!in_array($value, $del_values)){
// $result[$key] = $value;
//}
//if($this->validete($value)){
// $result[$key] = $value;
//}
}
return $result
A one-liner using the or
operator:
($key = array_search($del_val, $messages)) !== false or unset($messages[$key]);
As per your requirement "each value can only be there for once" if you are just interested in keeping unique values in your array, then the array_unique()
might be what you are looking for.
Input:
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
Result:
array(2) {
[0] => int(4)
[2] => string(1) "3"
}
I think the simplest way would be to use a function with a foreach loop:
//This functions deletes the elements of an array $original that are equivalent to the value $del_val
//The function works by reference, which means that the actual array used as parameter will be modified.
function delete_value(&$original, $del_val)
{
//make a copy of the original, to avoid problems of modifying an array that is being currently iterated through
$copy = $original;
foreach ($original as $key => $value)
{
//for each value evaluate if it is equivalent to the one to be deleted, and if it is capture its key name.
if($del_val === $value) $del_key[] = $key;
};
//If there was a value found, delete all its instances
if($del_key !== null)
{
foreach ($del_key as $dk_i)
{
unset($original[$dk_i]);
};
//optional reordering of the keys. WARNING: only use it with arrays with numeric indexes!
/*
$copy = $original;
$original = array();
foreach ($copy as $value) {
$original[] = $value;
};
*/
//the value was found and deleted
return true;
};
//The value was not found, nothing was deleted
return false;
};
$original = array(0,1,2,3,4,5,6,7,4);
$del_val = 4;
var_dump($original);
delete_value($original, $del_val);
var_dump($original);
Output will be:
array(9) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(3)
[4]=>
int(4)
[5]=>
int(5)
[6]=>
int(6)
[7]=>
int(7)
[8]=>
int(4)
}
array(7) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(3)
[5]=>
int(5)
[6]=>
int(6)
[7]=>
int(7)
}
here is one simple but understandable solution:
$messagesFiltered = [];
foreach ($messages as $message) {
if (401 != $message) {
$messagesFiltered[] = $message;
}
}
$messages = $messagesFiltered;
Success story sharing
array_diff()
would be slower as it's comparing two arrays, not simply searching through one likearray_search()
.0
or any other falsey value, it won't unset the value and your code won't work. You should test$key === false
. (edit- you got it)