Reputation: 1061
Basically I have the following code :
unset($items[array_search($i,$items)]);
When the key is not found the array_search returns false which is equivalent to returning 0, which results in deleting the element 0 of the array if an item value is not found.
Any Workaround for this?
Upvotes: 0
Views: 61
Reputation: 53502
$itemindex = array_search($i,$items);
if ($itemindex !== false) {
unset($items[$itemindex]);
}
Using separate variable and strict comparison you will only run unset() if an item was actually found from the array. Using !==
comparison to false you avoid confusing false with 0, since 0 is also a valid return value for array_search call, and in that case we do want to run unset().
Upvotes: 4
Reputation: 9884
array_search
returns the (first) key that contains the value, or false
if the value is not present. That means you need to check for false
before you call unset
, like so:
$ix = array_search($i,$items)
if($ix !== false) {
unset($items[$ix]);
}
Upvotes: 0
Reputation: 4921
if(($i = array_search($i,$items)) !== false) {
unset($items[$i])
}
is a possible workaround.
Upvotes: 1