0

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; ?>
6
  • Use a decent template engine (e.g. Smarty) Commented Dec 19, 2017 at 8:26
  • Not sure what is that? No php function that I can use? So that is the shortest code to do the sorting, right? Commented Dec 19, 2017 at 8:28
  • @Jows see my answer Commented Dec 19, 2017 at 8:31
  • A template engine will separate business logic (in your case, the sorting) from user interface (the HTML). It will make you application easier to read and maintain. Commented Dec 19, 2017 at 8:31
  • in the place of true show us the condition so that we can help in optimizing Commented Dec 19, 2017 at 8:32

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0
<?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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.