Skip to content
Advertisement

How to use foreach to return true/false

How can I use foreach to return true or false.

For example, this isn’t working.

function checkArray($myArray) {
    foreach( $myArray as $key=>$value ) {
       if(!$value == $condition) {
          return false;
       }
       else {
          return true;
       }
}

if ($checkArray == true) {
// do something
}

What is the correct syntax for using foreach as true/false function? If you can’t do it, could you use it to change an existing variable to true/false instead?

Advertisement

Answer

You would return true if the element was found/condition is true. And after the loop return false – if it had been found, this statement wouldn’t have been reached.

function checkArray($myArray) {
    foreach($myArray as $key => $value) {
        if ($value == $condition) {
            return true;
        }
    }
    return false;
}

if (checkArray($array) === true) {
    // ...
}

Of course true and false are interchangeable, depending on what output you expect.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement