Count number of iterations in a foreach loop

后端 未结 10 2018
礼貌的吻别
礼貌的吻别 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:52

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

    also this

    $count = 0;
    foreach($Contents as $items) {
      $count++;
      $items[number];
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 03:54
    foreach ($Contents as $index=>$item) {
      $item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15
    }
    
    0 讨论(0)
  • 2020-12-13 03:55
    foreach ($array as $value)
    {       
        if(!isset($counter))
        {
            $counter = 0;
        }
        $counter++;
    }
    

    //Sorry if the code isn't shown correctly. :P

    //I like this version more, because the counter variable is IN the foreach, and not above.

    0 讨论(0)
  • 2020-12-13 04:02
    $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
    
    0 讨论(0)
  • 2020-12-13 04:03

    Try:

    $counter = 0;
    foreach ($Contents as $item) {
              something 
              your code  ...
          $counter++;      
    }
    $total_count=$counter-1;
    
    0 讨论(0)
提交回复
热议问题