Odd behaviour with PHP's in_array function.

Posted by animuson on Stack Overflow See other posts from Stack Overflow or by animuson
Published on 2010-04-29T17:29:29Z Indexed on 2010/04/29 17:47 UTC
Read the original article Hit count: 419

Filed under:
|
|
|

I have a function that checks multiple form items and returns either boolean(true) if the check passed or the name of the check that was run if it didn't pass. I built the function to run multiple checks at once, so it will return an array of these results (one result for each check that was run). When I run the function, I get this array result:

Array ( [0] => 1 [1] => password [2] => birthday ) // print_r
array(3) { [0]=>  bool(true) [1]=>  string(8) "password" [2]=>  string(8) "birthday" } // var_dump

The 'username' check passed and the 'password' and 'birthday' checks both failed. Then I am using simple in_array statements to determine which ones failed, like so:

$results = $ani->e->vld->simulate("register.php", $checks);
die(var_dump($results)); // Added after to see what array was being returned
if (in_array("username", $results)) // do something
if (in_array("password", $results)) // do something
if (in_array("birthday", $results)) // do something

The problem I'm having is that the 'username' line is still executing, even those 'username' is not in the array. It executes all three statements as if they were all true for some reason. Why is this? I thought maybe that the bool(true) was automatically causing the function to return true for every result without checking the rest of the array, but I couldn't find any documentation that would suggest that very odd functionality.

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays