[php] Count number of iterations in a foreach loop

How to calculate how many items in a foreach?

I want to count total rows.

foreach ($Contents as $item) {
    $item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}

This question is related to php foreach

The answer is


There's a few different ways you can tackle this one.

You can set a counter before the foreach() and then just iterate through which is the easiest approach.

$counter = 0;
foreach ($Contents as $item) {
      $counter++;
       $item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}

Try:

$counter = 0;
foreach ($Contents as $item) {
          something 
          your code  ...
      $counter++;      
}
$total_count=$counter-1;

Imagine a counter with an initial value of 0.

For every loop, increment the counter value by 1 using $counter = 0;

The final counter value returned by the loop will be the number of iterations of your for loop. Find the code below:

$counter = 0;
foreach ($Contents as $item) {
    $counter++;
    $item[number];// if there are 15 $item[number] in this foreach, I want get the value `: 15`
}

Try that.


foreach ($array as $value)
{       
    if(!isset($counter))
    {
        $counter = 0;
    }
    $counter++;
}

//Sorry if the code isn't shown correctly. :P

//I like this version more, because the counter variable is IN the foreach, and not above.


You can do sizeof($Contents) or count($Contents)

also this

$count = 0;
foreach($Contents as $items) {
  $count++;
  $items[number];
}

foreach ($Contents as $index=>$item) {
  $item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15
}

count($Contents);

or

sizeof($Contents);

You don't need to do it in the foreach.

Just use count($Contents).


$Contents = array(
    array('number'=>1), 
    array('number'=>2), 
    array('number'=>4), 
    array('number'=>4), 
    array('number'=>4), 
    array('number'=>5)
);

$counts = array();

foreach ($Contents as $item) {
    if (!isset($counts[$item['number']])) {
        $counts[$item['number']] = 0;
    }
    $counts[$item['number']]++;
}

echo $counts[4]; // output 3