美文网首页
array_search 使用注意事项

array_search 使用注意事项

作者: zshanjun | 来源:发表于2017-06-28 17:35 被阅读37次

    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; 
    }
    
    

    转载自:

    相关文章

      网友评论

          本文标题:array_search 使用注意事项

          本文链接:https://www.haomeiwen.com/subject/kyoucxtx.html