array_search 使用注意事项

2017-06-28  本文已影响37人  zshanjun

Just something that will probably save time for many new developers: beware of interpreting FALSE and TRUE as integers.
For example, a small function for deleting elements of an array may give unexpected results if you are not fully aware of what happens:


<?php

function remove_element($element, $array)
{
   //array_search returns index of element, and FALSE if nothing is found
   $index = array_search($element, $array);
   unset ($array[$index]);
   return $array; 
}

// this will remove element 'A'
$array = ['A', 'B', 'C'];
$array = remove_element('A', $array);

//but any non-existent element will also remove 'A'!
$array = ['A', 'B', 'C'];
$array = remove_element('X', $array);
?>

The problem here is, although array_search returns boolean false when it doesn't find specific element, it is interpreted as zero when used as array index.

So you have to explicitly check for FALSE, otherwise you'll probably loose some elements:


<?php
//correct
function remove_element($element, $array)
{
   $index = array_search($element, $array);
   if ($index !== FALSE) 
   {
       unset ($array[$index]);
   }
   return $array; 
}


转载自:

上一篇 下一篇

猜你喜欢

热点阅读