Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in_array(1, array('1:foo')) returns TRUE? [duplicate]

Tags:

php

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
like image 426
Hong Truong Avatar asked Apr 16 '26 08:04

Hong Truong


1 Answers

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
like image 194
S.Pols Avatar answered Apr 18 '26 21:04

S.Pols