PHP a Better way to write an IF statement

PHP: Is there a better/cleaner way to write the following?

if (empty($simple_location) && empty($var_location)) {
    $loc = '<p>' . join(' : ', $links) . '</p>';
} else {
    $loc = '';
}
if(!empty ($simple_location)) {
    $loc_a = '<p>' . $simple_location. '</p>';
} else {
    $loc_a = '';
}
if(!empty ($var_location)) {
    $loc_b = '<p>' . $var_location. '</p>';
} else {
    $loc_b = '';
}

Open in new window

LVL 8
rgranlundAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
Better is somewhat subjective, but your logic could be made slightly more concise. Take a look at this:

$loc = $loc_a = $loc_b = "";

if (empty($simple_location) && empty($var_location)) {
    $loc = sprintf("<p>%s</p>", join(' : ', $links));
} else {
    $loc_a = empty($simple_location) ? "" : "<p>$simple_location</p>";
    $loc_b = empty($var_location) ? "" : "<p>$var_location</p>";
}

Open in new window

1
gr8gonzoConsultantCommented:
I agree with Chris - unless there are severe problems with the code (which there aren't here), "better" is often synonymous with "easier to read" or "easier to maintain." I might use the ternary operators to minimize the # of lines and check the results of $loc_a and $loc_b as the logic for $loc like this:

$loc_a = (!empty($simple_location) ? '<p>' . $simple_location. '</p>'     : '');
$loc_b = (!empty($var_location)    ? '<p>' . $var_location. '</p>'        : '');
$loc   = ( empty($loc_a . $loc_b)  ? '<p>' . join(' : ', $links) . '</p>' : ''); // If both locations are empty, fall back to $links

Open in new window

1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.