简体   繁体   中英

foreach within if /else

Currently I have this

// display all address with their associated phone numbers
    foreach ($data->address as $address) {
      if ($address->fullAddress) echo $address->fullAddress;
      if ($address->phones->PhoneNumber) echo $address->phones->PhoneNumber);
    }

but I need to add this as an alternative if the statements in the above clause are not met

// display all phone numbers if there is not an address
    if ($data->relatedPhone) echo $data->relatedPhone;

If none of the clauses are met I want nothing to display at all. So how can I combine the two?

here is a quick simple solution:

$addrfound=false;
foreach ($data->address as $address) {
  if ($address->fullAddress) { echo $address->fullAddress; $addrfound=true; }
  if ($address->phones->PhoneNumber) { echo $address->phones->PhoneNumber); $addrfound=true; } 
}

if (!$addrfound)
    if ($data->relatedPhone) echo $data->relatedPhone;

You can do an else if instead of another if :

if (foo) {
  echo "bar";
} else if (foo2) {
  echo "bar2";
} else {
  echo "foobar";
}

The last else is run only if all other if statements evaluate to false.

So in your case, I'd try this:

// display all address with their associated phone numbers
    foreach ($data->address as $address) {
      if ($address->fullAddress) {
        echo $address->fullAddress;
      } else if ($address->phones->PhoneNumber) {
        echo $address->phones->PhoneNumber;
      } else if ($data->relatedPhone) {
        echo $data->relatedPhone;
      }
    }

You need to structure your logic into if statements that are more easy to deal for you:

// display all address with their associated phone numbers
foreach ($data->address as $address) 
{
    $hasAddress = (bool) $address->fullAddress;
    $hasPhone = (bool) $address->phones->PhoneNumber;
    $isAddress = ??; # add your decision here, I can't see you specified it in your question.

    if ($hasAddress) echo $address->fullAddress;
    if ($hasPhone) echo $address->phones->PhoneNumber;

    // display all phone numbers if there is not an address
    if (!$isAddress) {
        if ($data->relatedPhone) echo $data->relatedPhone;
    }
}

You could create a flag to signal whether at least one of the conditions is met.

$flag = 0;
if (condition_1) {
  echo $output_1;
  $flag = 1;
}

if (condition_2) {
  echo $output_2;
  $flag = 1;
}

if (!$flag && condition_3) {
  echo $output_3;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM