How can I use foreach to return true or false.
For example, this isn’t working.
JavaScript
x
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.
JavaScript
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.