Volodymyr Kozubal Volodymyr Kozubal - 1 year ago 68
PHP Question

Weird array_search behaviour

I have the following code:

<?php

$ray = array(1, "aa" , 0);
echo "Index = " . array_search("I want to find this text", $ray);

?>


How to explain that the
array_search()
function returns existing index 2?

Answer Source

This is because array_search uses == to compare things. This makes PHP convert the operands so that their types match.

1 == "I want to find this text"
"aa" == "I want to find this text"
0 == "I want to find this text"

In the 1st and 3rd ones, PHP needs to convert "I want to find this text" to a number so it can compare. When converting a string to a number, PHP reads from the beginning of the string and stops at the first non-numeric character. So "I want to find this text" is converted to 0.

So the comparisons made are

1 == "I want to find this text" => 1 == 0 => false
"aa" == "I want to find this text" => false
0 == "I want to find this text" => 0 == 0 => true

And, that's why you get 2.

To fix this, do this: array_search("I want to find this text", $ray, true)

The 3rd parameter tells array_search to use === instead. This does not convert types, instead it compares them too. That will give you FALSE since nothing matches "I want to find this text" in both type and value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download