计算 foreach 循环中的迭代次数

Count number of iterations in a foreach loop(计算 foreach 循环中的迭代次数)
本文介绍了计算 foreach 循环中的迭代次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何计算一个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
}

这篇关于计算 foreach 循环中的迭代次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Why can#39;t I update data in an array with foreach loop?(为什么我不能用 foreach 循环更新数组中的数据?)
Foreach for arrays inside of an array(Foreach 用于数组内的数组)
PHP array get next key/value in foreach()(PHP 数组在 foreach() 中获取下一个键/值)
Using preg_match on a multidimensional array to return key values arrays(在多维数组上使用 preg_match 返回键值数组)
php foreach as key, every two number as a group(php foreach 为key,每两个数字为一组)
Treat a PHP class that implements Iterator as an array(将实现 Iterator 的 PHP 类视为数组)