Count logs with foreach PHP

2

Well it's quite simple I suppose, but the point is that I want to count the records in the database, in this case I have 2 in the DB, and when I put the foreach and see it in the table it shows me the 2 records but with the number 2, when it should be 1,2,3,4 .. consecutive ... in this example I should show them 1,2 ..

The table with 2 records

The foreach in PHP: /

foreach($usuarios as $key => $value){

   echo '<tr>
        <td>'.count($usuarios).'</td>
        <td>'.$value["nombres"].'</td>
        <td>'.$value["apellidos"].'</td>
        <td>'.$value["correo"].'</td>
        <td>'.$value["usuario"].'</td>';
    
asked by Jonathan 21.08.2018 в 23:10
source

3 answers

0

one way is like this:

//variable que almacenara los valores en cada ciclo
$contador=1;
foreach($usuarios as $key => $value){

    echo '<tr>
  <td>'.$contador.'</td>
  <td>'.$value["nombres"].'</td>
  <td>'.$value["apellidos"].'</td>
  <td>'.$value["correo"].'</td>
  <td>'.$value["usuario"].'</td>';

  //se incrementa el valor para que el proximo ciclo valga uno mas
  $contador= $contador + 1; 

I hope you serve ... you tell me!

    
answered by 21.08.2018 / 23:17
source
1

Yes, it's quite simple, you can get the index of the loop as follows:

 <?php
 foreach($array as $key => $item){
  echo $key . ":" . $item . "<br>";
}
?>

Another option is to define an incremental variable, and only the samples where you need:

$i=0;
foreach ($rows as $key => $row) { 
echo $row['id']; 
echo $row['firstname']; 
echo $row['lastname']; 
echo $i;
$i++;
}

I hope I helped you. Good luck!

    
answered by 21.08.2018 в 23:16
1

if it is an indexed array this would be perfect because the variable $key carries the index

foreach($usuarios as $key => $value){    
                  echo '<tr>
                <td>'.$key+1.'</td>
    
answered by 21.08.2018 в 23:17