Jess McKenzie
Jess McKenzie

Reputation: 8385

Using if with my foreach structure

I am using the following structure for my foreach how would I use an if statement within the same format?

<?php foreach($property as $section):?>


    if(!empty($section))
    {
      echo <p>data here </p>;
    }else{
      html
    }

<?php endforeach;?>

Upvotes: 0

Views: 220

Answers (6)

tomexsans
tomexsans

Reputation: 4527

SHORTHAND :

<?php foreach($property as $section):?>
    <?php if(!empty($section)):?>
      <p>data here </p>;
    <?php else: ?>
      html
    <?php endif;?>
<?php endforeach;?>

OTHER:

<?php foreach($property as $section)
 {
   if(!empty($section))
   {
     echo '<p>data here </p>';
   }else{
       echo 'html';
   }
 }
?>

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

<?php foreach($property as $section):
    if(!empty($section)):
      echo "<p>data here </p>";
    endif;
endforeach;?>

OR

<?php foreach($property as $section):
    if(!empty($section)):
      echo "<p>data here </p>";
    else:
       echo "html";
    endif;
endforeach;?>

See: Alternative Syntax

Upvotes: 3

nico gawenda
nico gawenda

Reputation: 3748

This is an example containing }elseif{ also:

<?php foreach($property as $section):?>

<?php    if(!empty($section)): ?>

      <p>data here </p>

<?php   elseif ([another condition]): ?>

      ...

<?php   else: ?>

      html

<?php   endif: ?>

<?php endforeach;?>

The entire documentation is here: http://php.net/manual/en/control-structures.alternative-syntax.php

Upvotes: 0

th3falc0n
th3falc0n

Reputation: 1427

I think best solution for this is:

<?php
foreach($property as $section) {
    if(!empty($section))
    {
        echo '<p>data here </p>';
    }
    else
    {
        ?>
        <div id="dosome">really crazy html stuff here</div>
        <?php
    }
}
?>

Upvotes: 0

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

I think you are looking for this.

<?php foreach($property as $section): ?>
    <?php
        if(!empty($section)) :
            echo <p>data here </p>;
        else :
            html
        endif;
endforeach; ?>

Upvotes: 0

Antony
Antony

Reputation: 15106

Not sure what you mean, but you don't have valid php.

foreach($property as $section) {
    if(!empty($section))
    {
      echo '<p>data here </p>';
    }else{
      echo 'html';
    }
}

Upvotes: 1

Related Questions