计算 foreach 循环中的迭代次数

2021-12-26 00:00:00 foreach php

如何计算一个foreach中有多少个项目?

How to calculate how many items in a foreach?

我想计算总行数.

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

推荐答案

如果你只想找出数组中元素的数量,使用 count.现在,回答您的问题...

If you just want to find out the number of elements in an array, use count. Now, to answer your question...

如何计算一个foreach中有多少个项目?

How to calculate how many items in a foreach?

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

如果你只需要循环内的索引,你可以使用

If you only need the index inside the loop, you could use

foreach($Contents as $index=>$item) {
    // $index goes from 0 up to count($Contents) - 1
    // $item iterates over the elements
}

相关文章