Jows
Jows

Reputation: 897

PHP If else sorting without repeating HTML

I'm searching and looking if I can minimize this code. I want to sort order if the condition is true the content come first and then the image and if false the image come first.

<?php if(true): ?>
 <div class="col-md-6">Text Content</div>
 <div class="col-md-6">Image</div>
<?php else: ?>
 <div class="col-md-6">Image</div>
 <div class="col-md-6">Text Content</div>
<?php endif; ?>

Upvotes: 0

Views: 73

Answers (3)

JJJJ
JJJJ

Reputation: 1358

You can use ternary operator

Solution:

<?php
$flip   = true;
$text   = 'Text Content';
$image  = 'Image';
?>
<div class="col-md-6"><?php echo $flip ? $text: $image; ?></div>
<div class="col-md-6"><?php echo $flip ? $image: $text; ?></div>

Result with true condition

Text Content 
Image

Upvotes: 3

Progrock
Progrock

Reputation: 7485

<?php
$items = [
    '<div class="col-md-6">Text Content</div>',
    '<div class="col-md-6">Image</div>',
];

$reverse = true;
array_map('printf', $reverse ? array_reverse($items) : $items);

Or:

print $reverse
    ? $items[1] . $items[0]
    : $items[0] . $items[1];

Upvotes: 0

Jordi Nebot
Jordi Nebot

Reputation: 3401

If you're using Bootstrap (I'm guessing for your col-md- classes) you could use reordering classes.

<div class="row">
    <div class="<?= $condition ? 'order-2 ' : '' ?>col-md-6">Text Content</div>
    <div class="col-md-6">Image</div>
</div>

Upvotes: 0

Related Questions