Welcome Guest, Not a member yet? Register   Sign In
doing if statement around the first part of array
#1

Hi, 

I am trying to figure out how to do an if statement that the first one in the array has a different layout that the rest.

Here is my example:

Code:
<?php foreach ($x as $y) : ?>
   <?php if (This is the part I cannot figure.) : ?>
     <div class="col-sm-6 col-md-12">
        ...
     </div>
  <?php else : ?>
     <div class="col-sm-6 col-md-4">
        ...
     </div>
  <?php endif; ?>
<?php endforeach; ?>

So I want the first item in the array to have the col-sm-6 and col-md-12, but then all the others to have col-md-4 instead.

Just not sure how I can tell the if to look if its the first item [0]

Thanks,
Doomie
Reply
#2

Code:
<?php

$first = true;
foreach ($x as $y) : ?>
   <?php if ($first === true) {
$first = false;
?>
     <div class="col-sm-6 col-md-12">
        ...
     </div>
  <?php else : ?>
     <div class="col-sm-6 col-md-4">
        ...
     </div>
  <?php endif; ?>
<?php endforeach; ?>
Reply
#3

If you really want to use foreach, you can do it like this.

PHP Code:
<?php $first true?>
<?php 
foreach ($x as $y) : ?>
   <?php if ($first) : ?>
   <?php $first  false?>
     <div class="col-sm-6 col-md-12">
        ...
     </div>
  <?php else : ?>
     <div class="col-sm-6 col-md-4">
        ...
     </div>
  <?php endif; ?>
<?php 
endforeach; ?>
Reply




Theme © iAndrew 2016 - Forum software by © MyBB