0

my apologies if there's an answer to this on SO somewhere. I searched around with no avail.

I'm wondering if there's alternative syntax for else if with HTML inside exists. I know there's such alternative syntax for if and else, but couldn't find anything in the PHP documentation for else if.

Right now I have this code:

<?php if($err) : ?>
    <div class="alert-failure"><?php echo "Error: " . $err; ?></div>
<?php endif; ?>
<?php if ($success): ?>
    <div class="alert-success"><?php echo "Success: " . $success; ?></div>
<?php endif; ?>

But this seems illogical since my app won't be having an error if it's successful. Is there a way to use else if here? Thanks in advance!

4

2 Answers 2

4

You could use Ternary it is simple, easy to read, and would look like this:

$value = ($condition) ? 'Truthy Value' : 'Falsey Value';

What Are The Advantages of Ternary Logic?

There are some valuable advantages to using this type of logic:

  • Makes coding simple if/else logic quicker

  • You can do your if/else logic inline with output instead of breaking your output building for if/else statements

  • Makes code shorter

  • Makes maintaining code quicker, easier
3
1

Another way would be -

<?php ($err) ? '<div class="alert-failure">Error: ' . $err . '</div>' : 
(($success) ? '<div class="alert-success">Success: ' . $success . '</div>' : '') ?>

It is somewhat similar like -

if($err) { //... }
elseif($success) { //... }
4
  • ugly imo, whats with the additional () wraps, add a few more, go on ;p... Jun 13, 2017 at 6:51
  • The additionals () are for understanding the groupings. also helps when it minds the operator precision. Thanks. Jun 13, 2017 at 6:53
  • Thank you for this! II feel silly for not realizing I could put the html as a string inside Ternary. My only gripe with this sort of solution is I feel that readability suffers. Although I suppose I can add a comment explaining this so it doesn't have to be deciphered.. Jun 13, 2017 at 6:57
  • I had to surround the output in a print() statement for this to output HTML. I discarded the extra parenthesis as well as they weren't necessary in this case. You may want to modify your future for the benefit of anybody who stumbles upon this in the future! Jun 13, 2017 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.