Why does in_array (1, array ('1: foo')) return TRUE?

1 is not in array (), the code is expected to return FALSE instead of TRUE. Do you know, why?

<?php
var_dump(in_array(1,  array('1:foo'))); // TRUE, why?
var_dump(in_array('1',  array('1:foo'))); // FALSE

      

+3


source to share


2 answers


As @knittl said, it has to do with the type of coercion. What's happening:

var_dump(in_array(1,  array('1:foo')));
//PHP is going to try to cast '1:foo' to an integer, because your needle is an int.

      

Casting (int) '1: foo' which results in integer 1, so we practically got this:



var_dump(in_array(1,  array(1))); //Which is TRUE

      

And the second statement is false. This is not true because they are both the same and PHP no longer tries to make actors. And of course "1" is not the same as "1: foo"

var_dump(in_array('1',  array('1:foo'))); //Which is FALSE

      

+6


source


Since you are comparing int

with string

, and the string is type-leading to int

- and since the first (or any first seq of chars) element of this string is a number and the next is not part of any int representation - it changes to that element = 1.

http://php.net/manual/en/language.types.type-juggling.php



var_dump(in_array(1233,  array('1233:123')));   //also True

      

+1


source







All Articles