1

I have this foreach, which matches a postal code $searchvalue to an array of districts. The if statement does its job and executes succesfully, if there is no else.

However, when I uncomment the else, then the else is always executed.

Why is this the case?

foreach ($districts['district'] as $district) { if (in_array($searchvalue, $district['postalcodes'])) { //Search for known Postal Code $emails[] = $district['email']; //Assign new mail address $notification['to'] = implode("",$emails); //Continue sending email return $notification; //this succeeds without the else below. When the Else is uncommented, this is not executed. } else { //No known postal code found, fallback echo "no valid postal code found, fallback"; $notification['to'] = $defaultaddress; return $notification; } } 
3
  • Show us your data set, we can't tell if the if statement is true. Commented Oct 23, 2017 at 13:55
  • your for loop repeated many times thats why its gone else part Commented Oct 23, 2017 at 13:56
  • What are the values of $searchvalue, $district['postalcodes'] ? can you do a dump before the if ? Commented Oct 23, 2017 at 13:56

1 Answer 1

6

Your foreach is going to be stepping through multiple records, so some are going to match and some aren't. Having else return something will cease execution of the foreach so the first non-matching record will stop the loop without evaluating all the rest of the entries.

You appear to want it to return $notification; if there's a match anywhere in the array, so move the else logic outside of the foreach:

foreach ($districts['district'] as $district) { if (in_array($searchvalue, $district['postalcodes'])) { //Search for known Postal Code $emails[] = $district['email']; //Assign new mail address $notification['to'] = implode("",$emails); //Continue sending email return $notification; //this succeeds without the else below. When the Else is uncommented, this is not executed. } } //No known postal code found, fallback echo "no valid postal code found, fallback"; $notification['to'] = $defaultaddress; return $notification; 

(Side note: You may want to consider what should happen if multiple records match. Right now, only the first matching one would receive an email - the rest will be ignored. A return may not be the ideal action here, depending on your goals and the data.)

Sign up to request clarification or add additional context in comments.

2 Comments

keypoint: move the "unknown-code" behind the foreach, not in the else-case. (else it will return after first unknown match)
Thx guys! Can't believe this was so simple... It works now :) @ceejayoz, there will always be a single match, so the code is correct now for the current use case. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.