Matthew Woodard
Matthew Woodard

Reputation: 754

How to simplify this PHP conditional statement?

I am trying to understand a simple / better way of coding something like this php conditional statement.

<?php if (count($foo_bar) > 1) : ?>

    <div class="myDiv1">
      Hello!
    </div>

<?php endif; ?>

<?php if (count($foo_bar) == 1) : ?>

    <div class="myDiv2">
      Goodbye!
    </div>

<?php endif; ?>

Looking for example, and explanation as to why it may be better. Thanks!

Upvotes: 2

Views: 140

Answers (4)

JC Sama
JC Sama

Reputation: 2204

First, you should the count function only once. Second, reduce the duplicated HTML blocks.

<?php 
$countFooBar = count($foo_bar);
if ($countFooBar == 1){
    $message = 'Goodbye! !';
    $cssClass = 'class1';
}elseif( $countFooBar > 1){
    $message = 'Hello!'
    $cssClass = 'class2';
}
?>

<div class="<?php echo $cssClass ?>">
  <?php echo $message; ?>
</div>

Upvotes: 1

RiggsFolly
RiggsFolly

Reputation: 94642

Quite simply in this specific situation you dont need the second if as it can be accomplished with a simple if else

<?php if (count($foo_bar) > 1) : ?>

    <div class="myDiv1">
      Hello!
    </div>

<?php else: ?>

    <div class="myDiv2">
      Goodbye!
    </div>

<?php endif; ?>

Upvotes: 2

James Dewes
James Dewes

Reputation: 387

Try using an elseif like below. A bit more compact than the 2 statements.

<?php if (count($foo_bar) == 1) : ?>
<div class="myDiv2">
  Goodbye!
</div>
<?php     elseif(count($foo_bar) > 1): ?>
<div class="myDiv1">
  Hello!
</div>
<?php     endif; ?>

Upvotes: 1

Naincy
Naincy

Reputation: 2943

<?php
     $class = 'myDiv2'; 
     $msg = 'GoodBye!';
     if (count($foo_bar) > 1) {
       $class = 'myDiv1';
       $msg = 'Hello!';
     }
?>

    <div class="<?php echo $class; ?>">
     <?php echo $msg; ?>
    </div>

Upvotes: 2

Related Questions