3

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
Hong Truong
  • 821
  • 7
  • 11
  • 8
    [Type coercion](http://codepad.org/cBoG2HDz). `1 == '1:foo'` (because `(int)'1:foo' === 1`) – knittl Nov 19 '14 at 06:59
  • 1
    http://php.net/manual/en/function.in-array.php You should check the doc pages. in_array requires a third argument to do type-sensitive checks. – TonyArra Nov 19 '14 at 07:05

2 Answers2

6

As @knittl already said, this is because type coercion. What is 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.

The cast is (int)'1:foo' which results to the integer 1, so practically we got this:

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

And the second statement is false. It's false because they are both the same type and PHP doesn't try any cast anymore. And ofcourse "1" is not the same as "1:foo"

var_dump(in_array('1',  array('1:foo'))); //Which is FALSE
S.Pols
  • 3,414
  • 2
  • 21
  • 42
1

Because you are comparing int to string, and the string is type-casted to int- and since first (or any first seq of chars) element of that string is a number and next is not part of any int representation - it change to that element = 1.

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

var_dump(in_array(1233,  array('1233:123')));   //also True
kwarunek
  • 12,141
  • 4
  • 43
  • 48