Matt Whitehead Matt Whitehead - 3 months ago 12
PHP Question

Return true if and only if all values in array are true?

So I have an array that contains all of the function calls to check the input of a form. I then have a foreach loop through the array to see if the returns from the validate functions are true or false. Depending on that outcome the function that the foreach is in returns either true or false. The problem I'm trying to figure out is how to return true just once if all of the validate functions come back true.

Here is my code:

public function valInputs()
{
$valArray = array(
valName($firstName),
valName($lastName),
valPhone($phone),
valEmail($email)
); // these functions return true/false depending on validation

foreach($valArray as $value)
{
if(!$value)
{
return false;
break;
}
else
{
return true; // the problem is, true gets returned X number of times
}
}
}


Any ideas on how to keep true from returning multiple times? Thank you for any help.

Answer

The return call stops the foreach loop AND the function. You can in fact just return true beneath the loop:

foreach($valArray as $value)
{
    if(!$value)
    {
        return false;
        // break is not needed, and should NOT be used in this case,
        // as it stops the foreach loop.
        // It will never be reached anyways, seeing how you return false just above.
    }
}
return true;

If it reaches the end of the loop, it means it hasn't returned false. Hence it should return true.