0

I have the strangest php behavior I've never noticed before:

$array =array(0,1,2, 'parent');
   foreach ($array as $value)
{
    if ($value=='parent')
    {
        echo $value;
        echo '<br>';
        continue; 
    }

}
exit;

Will return

0
parent

I was wondering if anyone could explain to me why it matches the 0 to the string 'parent'?

Funk Forty Niner
  • 73,764
  • 15
  • 63
  • 131
atwellpub
  • 4,732
  • 10
  • 35
  • 52
  • 6
    Read the relevant section of the PHP documents on [loose comparisons and typecasting](http://www.php.net/manual/en/types.comparisons.php) – Mark Baker Jan 25 '14 at 01:36
  • 1
    try to var_dump($value);instead of echo. You will get clearer picture. As @Ignacio Vazquez-Abrams "Because that's how PHP rolls: Like a square wheel." – pregmatch Jan 25 '14 at 01:43

2 Answers2

1

what Mark said but to expound, 0 is a number so the == operator casts the 'parent' string to a number, which gives 0. The == operator does not care about type. So they match.

troseman
  • 1,655
  • 18
  • 19
1

The "==" operator in php does not compare the type of the objects, it converts the objects to another type. So in your case you are comparing a numerical object with a string object. So it changes the type of your string 'parent'. Since that string does not contain any numerical value it probably changes it to 0. See http://il.php.net/manual/en/language.operators.comparison.php and http://il.php.net/manual/en/language.types.string.php#language.types.string.conversion for more explanations

kapukinz
  • 166
  • 11