Count the variable $ i of a flower cycle

0

Hello good day I have a cycle so what I need is to count how many items the for example 0,1,2,3,4,5,6 = 7. brings me and get the result that is 7.

if (isset($_SESSION['carrito'])) {
  $datos = $_SESSION['carrito'];
  for ($i=0; $i < count($datos); $i++) { 

  }
}

is to create the notification of how many products are in the cart. example of the code.

<div class="col-md-10">
<?php 
  $total = 0;
  if (isset($_SESSION['carrito'])){
      $datos = $_SESSION['carrito'];
      $total = 0;
      for ($i=0; $i<count($datos); $i++) { 
  ?>
    <div class="producto">
        <div class="card border-success" style="width: 13rem;">
            <img class="card-img-top" src="admin/productos/<?php echo $datos[$i]['Imagen'];?>" width="20" height="150" alt="<?php echo $datos[$i]['nombre_producto'];?>" title="<?php echo $datos[$i]['nombre_producto'];?>">
            <div class="card-body">
                <h5 class="card-title"><span class="text-info">Precio:&nbsp;$<?php echo $datos[$i]['Precio'];?></span></h5>
                <span>Cantidad:&nbsp;</span>
                <input type="text" value="<?php echo $datos[$i]['Cantidad'];?>" data-precio="<?php echo $datos[$i]['Precio'];?>" data-id="<?php echo $datos[$i]['Id'];?>" class="cantidad form-control" size="2" maxlength="2" required onKeyPress="return SoloNumeros(event);" onPaste="return false">
                <center><span class="text-success subtotal">Subtotal:&nbsp;$<?php echo $datos[$i]['Cantidad']*$datos[$i]['Precio'];?></span></center>
                <center><a href="#" class="eliminar btn btn-danger" data-id="<?php echo $datos[$i]['Id']?>"><span class="icon-bin"></span>ELIMINAR</a></center>
            </div>
        </div>
    </div>
    
asked by jorge enrique chan castillo 10.09.2018 в 13:43
source

3 answers

1

The for loop itself is giving you the solution:

count($datos);

The for will do as many iterations as there are products, so it is initialized to $i = 0 and iterates up to $i<count($datos) which is not anything other than the number of products.

    
answered by 10.09.2018 в 14:00
1

Well, I think it's enough with something you're already doing: count($datos) gives you the total number of elements. If you do it directly on the session variable, you avoid initializing a variable: count($_SESSION['carrito']) (Provided the session has a cart, of course)

    
answered by 10.09.2018 в 14:00
0

If in the $datos array there are only text strings, numbers or simple values, you can use $result = count($datos) and you save doing the for. If there are other arrays inside the array, things get complicated.

    
answered by 10.09.2018 в 14:03