Link to home
Start Free TrialLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

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

ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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