gieldops
gieldops

Reputation: 385

Is there any way to do this more efficiently in PHP?

First of all, sorry for the title, I didn't know how to describe my problem.

I have the following piece of code (simplified).

if ($red && $italic)
    echo "<tr class='red italic'>";
elseif ($italic)
    echo "<tr class='italic'>";
elseif ($red)
    echo "<tr class='red'>";
else
    echo "<tr>";

Is there a way to simplify this, i.e. not use 8 lines? I know that's not very important but I was wondering if it could be possible.

Thanks!

Upvotes: 0

Views: 31

Answers (2)

rjdown
rjdown

Reputation: 9227

Yes, you can "simplify" it.

echo '<tr' . ($red || $italic ? ' class="' . ($red ? 'red' : '') . ($italic ? ' italic' : '') . '"' : '') . '>';

If you're not worried about sending an empty class, this can be shrunk:

echo '<tr class="' . ($red ? 'red' : '') . ($italic ? ' italic' : '') . '">';

You could write an entire app in one line if you wanted. But should you? Readability is extremely important.

If you're looking to rewrite your code to make it look less repeated, there are loads of options.

This method is the same number of lines as the original but allows you to easily add another class by changing one part

$classes = array('red', 'italic');
$used_classes = array();
foreach ($classes as $class) {
    if ($$class) {
        $used_classes[] = $class;
    }
}
echo '<tr class="' . join(' ', $used_classes) . '">';

Upvotes: 2

user3835115
user3835115

Reputation:

You could use a switch.

$type = 'iandr';

switch ($type) {
    case iandr:
        echo'<tr class="red italic">';
       break;

    case i:
        echo'<tr class="italic">';
       break;

    case r:
        echo'<tr class="red">';
       break;

    default:
        code to be executed here if $type is different to the above cases.
}

Personally i prefer using switches rather than if and else statements.

Upvotes: 0

Related Questions