2

I have the following code:

<pre>
<?php

$array['page'] = 'page';
$array['article'] = 0;
$array['other'] = 1;

var_dump($array);

$index0 = array_search(0, $array);

var_dump($index0);

$index1 = array_search(1, $array);

var_dump($index1);

?>
</pre>

With the following output:

array(3) {
  ["page"]=>
  string(4) "page"
  ["article"]=>
  int(0)
  ["other"]=>
  int(1)
}
string(4) "page"
string(5) "other"

As you see in the 'article' index of the array I have the value 0 (0 as a integer value), so I expect to have in the $index0 var the value 'article' but I obtain the value 'page', the first item in the array ($array[0]).

But if I try to obtain the index for the value 1 (1 as a integer value), the $index1 variable have the good value 'other'.

This is normal?

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
  • 1
    Look at the 3rd parameter of `array_search()`. – Rizier123 Aug 17 '16 at 18:28
  • Sorry missed the var_dump() – The One and Only ChemistryBlob Aug 17 '16 at 18:30
  • @Rizier123 I know that the code works with `$index0 = array_search(0, $array, 1);` but why not works with my example? – Adrian Cid Almaguer Aug 17 '16 at 18:31
  • This is also covered in the dupe. By default PHP will do a loosely comparison and there `0` and any string are equal. See: http://stackoverflow.com/q/80646/3933332 – Rizier123 Aug 17 '16 at 18:33
  • 1
    Check the second table (loose comparison with `==`) on the [PHP type comparison](http://php.net/manual/en/types.comparisons.php) page and you'll find out that `'page' == 1` but `'page' !== 1`. That's the reason some PHP functions ([`in_array()`](http://php.net/manual/en/function.in-array.php), [`array_search()`](http://php.net/manual/en/function.array-search.php), [`array_keys()`](http://php.net/manual/en/function.array-keys.php)) have a third argument. (`bool $strict = false`) – axiac Aug 17 '16 at 18:42

0 Answers0