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
2
  • 8
    Type coercion. 1 == '1:foo' (because (int)'1:foo' === 1) Commented Nov 19, 2014 at 6:59
  • 1
    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. Commented Nov 19, 2014 at 7:05

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.