1

I was trying to find a value in a multi-array variable. It took too much time to find where was my bug...

Try this code:

$aa = array("nombre" => "HOLA", "v" => 0);
$bb = array("nombre" => "HOLB", "v" => 0);
$cc = array("nombre" => "HOLC", "v" => 0);
$dd = array($aa,$bb,$cc);

if (in_array("HOLA",array_column($dd,"nombre")))
     echo "in_array = yes";
else
     echo "in_array = no";

echo "<br>";

if (array_search("HOLA",array_column($dd,"nombre")))
     echo "array_search = yes";
else
     echo "array_search = no";

the answer I get is:

in_array = yes
array_search = no

It is this a supposed behavior?

1
  • 2
    Yes, it is expected behaviour; because it's finding the value at key 0, which you're then testing for truthinesss, and 0 == false. Use if (array_search("HOLA",array_column($dd,"nombre")) !== false) Commented May 9, 2017 at 16:19

2 Answers 2

2

Yes. The documentation for array_search states the following:

Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

The value you are getting is 0, which is failing your if, but is the correct answer.

Sign up to request clarification or add additional context in comments.

Comments

1

array_sarch will return the index at which it finds the result, so in your case 'HOLA' is at the 0 index which makes the condition fail. You should check it like this

if (array_search("HOLA",array_column($dd,"nombre")) !== false)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.