PHP in_array() / array_search() odd behaviour

前端 未结 2 1783
栀梦
栀梦 2020-11-22 08:05

I have found some odd behaviour while I was using the PHP function in_array(). I have an array like this:

$arr = [TRUE, \"some string\", \"somet         


        
相关标签:
2条回答
  • 2020-11-22 08:10

    You are right, the boolean can indeed cause this. Set the strict flag in the in_array function, this way also the type of the element is checked (basically the same as using ===):

    if (in_array("username", $results, true)) // do something
    if (in_array("password", $results, true)) // do something
    if (in_array("birthday", $results, true)) // do something
    
    0 讨论(0)
  • 2020-11-22 08:15

    This behaviour of the function in_array() and array_search() is not a bug, but instead well documented behaviour.

    Both functions have a 3rd optional parameter called $strict which by default is FALSE:

    bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

    mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

    Now what that means is that by default both functions use loosely(==) comparison to compare the values. So they only check if the values are the same after PHP type juggling and without checking the type. Because of that in your example TRUE == "any none emtpy string" evaluates to TRUE.

    So by setting the 3rd parameter to TRUE while calling the function you say that PHP should use strict(===) comparison and it should check value AND type of the values while comparing.

    See this as a reference: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

    0 讨论(0)
提交回复
热议问题