The number of iterations in the foreach loop

How to calculate how many elements in foreach?

I want to count the complete lines.

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

Thank.

+56
php foreach
Jun 02 2018-11-21T00:
source share
10 answers

First of all, if you just want to know the number of elements in an array, use count . Now, to answer your question ...

How to calculate how many elements in foreach?

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

You can also see the answers here:

  • How to find the foreach index
+108
Jun 02 2018-11-21T00:
source share

You do not need to do this in foreach .

Just use count($Contents) .

+43
Jun 02 2018-11-21T00:
source share
 count($Contents); 

or

 sizeof($Contents); 
+16
Jun 02 2018-11-11T00:
source share
 foreach ($Contents as $index=>$item) { $item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15 } 
+16
Dec 16 '13 at 13:16
source share

There are several different ways to solve this problem.

You can set the counter before foreach (), and then just iterate, 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 } 
+4
Jun 02 2018-11-21T00:
source share
 $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 
+1
Jun 02 2018-11-21T00:
source share
 foreach ($array as $value) { if(!isset($counter)) { $counter = 0; } $counter++; } 

// Sorry if the code is not shown correctly .: P

// I like this version more, because the counter variable is in foreach, not higher.

+1
Sep 10 '13 at 10:13
source share

Try:

 $counter = 0; foreach ($Contents as $item) { something your code ... $counter++; } $total_count=$counter-1; 
+1
May 27 '15 at 10:58
source share

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

also this

 $count = 0; foreach($Contents as $items) { $count++; $items[number]; } 
+1
Oct 05 '16 at 6:39
source share

Imagine a counter with an initial value of 0 .

For each cycle, increase the counter 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 this.

0
Aug 19 '19 at 12:01
source share



All Articles