简体   繁体   中英

PHP's in_array unexpected result

When I execute this small piece of PHP code:

php -r "echo(in_array(0, array('aaa', 'bbb')));"

That echoes true ...

Of course I have the good return value if I add the strict flag to in_array , but I just can't understand why it returns true (I can't !!). If anyone can explain me I will sleep well tonight.

PS: Sorry that this is just about curiosity...

That's because for PHP this code will return true

0 == 'aaa'

So without strict checking PHP will find your value in given array.

Also, check out this code:

   var_dump(0 == 'aaa');
   var_dump(0 === 'aaa');
   var_dump(in_array(0, array('aaa', 'bbb')));
   var_dump(in_array(0, array('aaa', 'bbb'), true));

The last version allows strict type comparison so it will work as expected, that is return false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM