0

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?

Faouzi FJTech
  • 981
  • 3
  • 13
  • 27

3 Answers3

4
$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().

eis
  • 51,991
  • 13
  • 150
  • 199
1
if(($i = array_search($i,$items)) !== false) { 
    unset($items[$i]) 
}

is a possible workaround.

netvision73
  • 4,831
  • 1
  • 24
  • 30
  • 2
    original function does not modify $i: it is the value to be looked for, so you shouldn't assign to it. – eis Aug 13 '13 at 09:06
  • 1
    this overwrites `$i`, so it can impact some other logic. also, while there is one less line here than in @eis's code, it doesnt benefit, and in fact code looks less readable. – poncha Aug 13 '13 at 09:06
  • Please improve this answer with the intent to educate future readers. Code-only answers are low-value on StackOverflow. – mickmackusa Feb 19 '18 at 13:52
0

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]);
}
Arjan
  • 9,784
  • 1
  • 31
  • 41