Count the percentage of the number of the current iteration in a foreach loop

后端 未结 5 2015
别那么骄傲
别那么骄傲 2021-01-29 07:59

I am trying to build up a script that gets the current percentage of the iteration of a loop.

I have :



        
相关标签:
5条回答
  • 2021-01-29 08:22

    Firstly, you have to get the total amount of iterations. count() helps in this case.

    <?php
        $counter = 0;
        $total = count($yourArray);
    
        // ...
          // inside the loop
          $counter++;
          $percentage = $counter/$total;
    

    Live example

    Converting 0.xx to x % is left as an exercise for the reader.

    0 讨论(0)
  • 2021-01-29 08:31

    You can do exactly what are you asking in this way

    $counter = 0;
    $length  = count($array);
    
    foreach ($array as $value) {
    
    $counter=$counter+1;
    for ($stepvvx = 10; $stepvvx <= 100; $stepvvx=$stepvvx+10)
        {
    if ($counter==intval(($length*$stepvvx)/100)){
        echo "<br>$stepvvx %";
    }
    
    # do your task here
    
    }
    
    0 讨论(0)
  • 2021-01-29 08:35

    Store the total length of the array in a variable and use that to calculate the percentage. Watch that you prefix your variables with $. Also, you might want to name your variables more appropriately—an array isn't a key.

    $counter = 0;
    $length  = count($array);
    
    foreach ($array as $value) {
        $counter++;
        $percentage = $counter / $length;
    }
    
    0 讨论(0)
  • 2021-01-29 08:37

    you need to do ($total/$iterations) * $counter like this code:

     $counter = 0;
     $total = 100;
     $iterations = count($key);
    
     foreach($key as value) {
          $counter++;
          $percentage = (($total/$iterations) * $counter)/100;
     }
    
    0 讨论(0)
  • 2021-01-29 08:42

    To calculate percentage, you take the current and divide it by the total, then multiply that value by 100, then round it off. I also take the floor value so that 99.7% doesn't round up to 100 since it's not truly complete yet.

        for($i=1;$i<=count($yourArray);$i++) {
          $percentage = floor(round( (($i / total) * 100), 1 ));
        }
    
    0 讨论(0)
提交回复
热议问题