Count number of iterations in a foreach loop

后端 未结 10 2019
礼貌的吻别
礼貌的吻别 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 04:11

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

    Just use count($Contents).

    0 讨论(0)
  • 2020-12-13 04:14

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

    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
    }
    
    0 讨论(0)
  • 2020-12-13 04:17
    count($Contents);
    

    or

    sizeof($Contents);
    
    0 讨论(0)
  • 2020-12-13 04:17

    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
    }
    
    0 讨论(0)
提交回复
热议问题