David David - 3 months ago 7
PHP Question

typesetting use classname in foreach php

<?php
$classNames = array('margin-2', 'margin-4', 'margin-2', 'margin-8');

if($productCatalogs != null){

$i = 0;

foreach($productCatalogs as $productCatalog){

$i++;

if($i % 2 == 0){

// if $i is even number
echo '<li class="{ use classname here }"><a href="#">Link name</a></li>';

} else {

// if $i is odd number
echo '<li><a href="#">Link name</a></li>';

}

}

}
?>


As above code, i want to use each $classNames value in foreach when $i is even number only, like first even number record use { margin-2 }, next even number record use { margin-4 }.

below is that code result i want,

<li></li> // if record is odd number, doesn't need class name
<li class="margin-2"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-4"></li>

<li></li> // if record is odd number, doesn't need class name
<li class="margin-2"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-8"></li>

<li></li> // if record is odd number, doesn't need class name
<li class="margin-2"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-4"></li>

...

Answer

Just use a counter variable as an index in your array and increment when you find an even number.Also if you have many elements you need to check if you reached the end of the array and reset your counter.Something like this:

    <?php
  $classNames = array('margin-2', 'margin-4', 'margin-2', 'margin-8');

  if($productCatalogs != null){

    $i = 0;
    $even_counter=0;

    foreach($productCatalogs as $productCatalog){

      $i++;

      if($i % 2 == 0){

         // if $i is even number
    echo '<li class="'.$classNames[$even_counter].'"><a href="#">Link name</a></li>';

    //when we reach the end of the array we reset our counter to 0
    $even_counter=($even_counter+1==count($classNames))?0:$even_counter+1;
      } else {

        // if $i is odd number
        echo '<li><a href="#">Link name</a></li>';

      }

    }

  }
?>
Comments