Count number of iterations in a foreach loop

后端 未结 10 2047
礼貌的吻别
礼貌的吻别 2020-12-13 03:41

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[n         


        
10条回答
  •  被撕碎了的回忆
    2020-12-13 03:53

    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.

提交回复
热议问题