user1302430
user1302430

Reputation: 352

PHP - If statement not working correctly in foreach loop

Hi I have this code here:

public function length($args) {
    if (isset($this->length)) {
        foreach ($this->length as $k => $v) {
            if (strlen($args[$k])>=$v[0] && strlen($args[$k])<$v[1]) {
                return true;
            } else {
                array_push($this->form_errors, $v[2]);
                return false;
            }
        }
    } else { 
        return true;
    }
}

I'm not sure why but its not working as expected. The foreach loop only loops through one of the $args[$k] even though there are 2 of them. Anyone have any idea whats going on? I'm writing this question in a hurry so if I need to explain anything else, please let me know.

Thanks!

Upvotes: 1

Views: 514

Answers (1)

Marc B
Marc B

Reputation: 360632

Your two return statements in both sides of the if() clause terminate the function on the first iteration of the loop. Either the strlen stuff is true and you return true, or they're false and you return false. regardless, the loop ends.

If you simply want to jump to the next iteration, then use continue instead, which'd allow the foreach to proceed.

Upvotes: 9

Related Questions