How to check the presence of certain values in an array?

1

I have the variable $search_dorms that returns me Array ( [0] => 1 [1] => 2 ) .

It can also return Array ( [0] => 1 [1] => 2 [2] => 3 )

Or simply Array ( [0] => 1 )

I'm trying to check the returned values but to no avail. I ask for help. The code I'm using is:

if(in_array(array('1'), $search_dorms)) {

    $search_dorms = 1;
    echo $search_dorms . "<br><br>";    

} elseif (in_array(array('1', '2'), $search_dorms)){

    $search_dorms = 2;
    echo $search_dorms . "<br><br>";        

}

How can I check if the values that can be strings or numbers are within array $search_dorms ? If you fix it, I'm trying to check more than 1 value simultaneously and that's what you're getting.

  

Another way to explain what I said above:

if(in_array(1, $search_dorms)) echo "Ok<br><br>";
if(in_array(array(1, 2), $search_dorms)) echo "Ok novamente<br><br>";

I'm trying to do this check. "Ok again" does not appear.

    
asked by anonymous 03.01.2016 / 19:23

1 answer

5

I took a look at the in_array documentation on link and from what I understood the "ok again "is not appearing for the following reason:

in_array(array(1, 2), $search_dorms);

is looking for an array that contains the two integers, 1 and 2, inside the $ search_dorms array and not a search for integer 1 and integer 2 on $ search_dorms. If you do so:

var_dump(in_array(array(1, 2), $search_dorms));

You will see that it returns bool (false) (The reason for not entering the if block), but if you do:

$search_dorms = array(1, 2, array(1,2));
$foo = array(1,2);
var_dump($foo, $search_dorms);

You will see that it will return bool (true).

It is also worth remembering that the third parameter of in_array () check the types. like this:

$search_dorms = array(1, 2, 3);
$foo = '1';
var_dump(in_array($foo, $search_dorms, true));

will return bool (false)

To solve your problem, I suggest that you put the & & inside the if.

if(in_array(1, $search_dorms) && in_array(2, $search_dorms)){...}

sources: in_array (): link var_dump (): link

    
03.01.2016 / 20:22