Search code examples
phparrays

Build a multi-line address string with conditional components


I had to make some changes to my app to work with a relationship change in my db.

Originally I had whats below for a 1::0-1 relationship

if ($model->address->AddressLine1) echo $model->address->AddressLine1.'<br />';
if ($model->address->AddressLine2) echo $model->address->AddressLine2.'<br />';
if ($model->address->city->Name) echo $model->address->city->Name;
if ($model->address->city->regionCode->RegionCode) echo ', '.$model->address->city->regionCode->RegionCode;

but had to change it to work with a 1::0-n relationship

foreach ($model->address as $al1)
foreach ($model->address as $al2)
foreach ($model->address as $al2)
foreach ($model->address as $city)
foreach ($model->address as $region) {
    echo $al1->AddressLine1.' '.$al2->AddressLine2.'<br/>'.$city->city->Name.' '.$city->city->regionCode->RegionCode;
}

I want to retain the functionality of the if in my original code. With the original code I was able to use

', '.

in

if ($model->address->city->regionCode->RegionCode) echo ', '. $model->address->city->regionCode->RegionCode;

to only add a comma after City only when a Region is present in the db.

So how can I get that back and utilize if within my array?


Solution

  • You only need one foreach loop — you're just iterating through a single array.

    You can stick the conditionals into the foreach loop, updating the variable name. This assumes that $model->address is an array. On each iteration $address will be set to a subsequent element of that array.

    foreach ( $model->address as $address ) {
        if ($address->AddressLine1) echo $address->AddressLine1.'<br />';
        if ($address->AddressLine2) echo $address->AddressLine2.'<br />';
        if ($address->city->Name) echo $address->city->Name;
        if ($address->city->regionCode->RegionCode) echo ', '.$address->city->regionCode->RegionCode;
    }
    

    For more information: