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 7
rgranlundAsked:
Who is Participating?
 
Chris StanyonCommented:
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
All Courses

From novice to tech pro — start learning today.