views:

129

answers:

2

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.

+2  A: 

You are right. "username" == true evaluates to true, causing in_array() to return true. Use the strict flag. That will cause the function to use "username" === true, which evaluates to false. In PHP, a string is true unless it is empty. And the === operator checks type in addition to value.

Fletcher Moore
Of course, something so simple... Thanks
animuson
+2  A: 

You are right, the boolean can indeed cause this. Set the strict flag in the in_array function, this way also the type of the element is checked (basically the same as using ===):

if (in_array("username", $results, true)) // do something
if (in_array("password", $results, true)) // do something
if (in_array("birthday", $results, true)) // do something
Felix Kling