当前位置:网站首页>Why in PHP_ Array (0, ['a','b','c']) returns true

Why in PHP_ Array (0, ['a','b','c']) returns true

2022-06-09 04:34:00 User 9076598

stay PHP in , Data meeting Automatic conversion type Then compare .

This may lead to some inexplicable phenomena :

in_array(0, ['a', 'b', 'c']) 
//  return bool(true), It is equivalent to that there are 0


array_search(0, ['a', 'b', 'c'])
//  return int(0), That is, the subscript of the first value 

0 == 'abc'
//  return bool(true), It is equivalent to equality 

Both of these expressions return true.

Intuitively ,0 Not in the array ['a', 'b', 'c'] in , It won't equal abc This string .

How could that return true Well ?

1 Type conversion

And the reason is that , Before comparison ,PHP Type conversion is done .

PHP The explanation on the official website :http://php.net/manual/en/language.types.string.php#language.types.string.conversion

string Data of type will be converted to int type , Then compare .

And if the string The first character of type data is not a number , It will be converted into 0. for example ,

echo intval("Bye");    //  Output 0

in_array() and array_search() The default is loose comparison , amount to ==, So you get true.

2 Strict comparison

How to get false Well ?

Compare strictly , as follows ,

in_array(0, ['a', 'b', 'c'], true) 
//  return false


array_search(0, ['a', 'b', 'c'], true)    
//  return false

0 === 'abc' 
//  return false

Force type comparison , So we can get accurate results .

3 false and null

that , If you use false and null What happens when compared to a string array ?

They will not be converted into int Type , So the result is :

in_array(null, ['a', 'b', 'c'])  
// return false

in_array(false, ['a', 'b', 'c']) 
// return false

4 Array has true

Another strange phenomenon :

in_array('a', [true, 'b', 'c'])       
//  return bool(true), It is equivalent to that there are characters in the array 'a'

array_search('a', [true, 'b', 'c'])
//  return int(0), Equivalent to finding the character 'a'

Why is that ?

It's easy to understand , Relatively loose , whatever string All equal to true.

To be unequal , The old , Compare strictly .

原网站

版权声明
本文为[User 9076598]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203021700496329.html