how can I know when is the last item in for

1

I have a problem in php I am trying to know when the last element is not generated the last element that would be

   <li class="separator">&nbsp;</li>
    <?php
    $rama_cat="40-20-01";
    $partes=explode('-',$rama_cat);
    $cantidad=count($partes);


    for ($i=0; $i < $cantidad; $i++) { ?>
    <li><a href="<?=$urlWeb;?>"><?=nombre_cat($partes[$i]);?></a></li>
    <?php
    foreach($partes as $elem) {
     if ($elem === reset($partes)) {
    echo '<li class="separator">&nbsp;</li>';
    }
    }
    }?>
    
asked by Matias 01.10.2018 в 03:55
source

2 answers

2

Try this :)

$array = ['40','20','01'];
$length  = count($array);

foreach($array as $num=>$elem) {
  echo ($num == $length-1) ? '' : '<li class="separator"> '.$elem.'</li>' ;
}

We go in parts:

Assuming that you already performed the explode function to $ parts, it returns an array like this ([0] = > 40 [1] = > 20 [2] = > 01)

$array = ['40','20','01'];

Now let's measure the length of the array with count () and save it in a variable

$length  = count($array);

The following part could be done in many ways, but in this case we are going to use a foreach and a ternary operator

    //comenzamos en ciclo 

    foreach($array as $num=>$elem) {

    //comenzamos a recorrer el array, $num nos servirá para contar el número de vuelta, $elemen contiene los datos del array

   //en esta parte pasamos al operador ternario establecemos nuestra condicional, en este caso le decimos que cuando $num sea igual a el tamaño del array menos 1 no nos imprima nada, de caso contrario imprimirá lo pedido. 

      echo ($num == $length-1) ? '' : '<li class="separator"> '.$elem.' posición  en array => '.$num.'</li>' ;


    }
    
answered by 01.10.2018 в 07:16
-1

If you look at this part:

$cantidad=count($partes);

If $ parts have 3 elements, then they will be in position 0,1,2 and count ($ parts) will give you 3; if it has 10 elements, they will be in the position: 0,1,2,3,4,5,6,7,8,9 respectively, and in addition, count ($ parts) will give you 10. If you notice, the last element will always be in count($partes) - 1

    
answered by 01.10.2018 в 04:39