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

后端 未结 5 2022
别那么骄傲
别那么骄傲 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条回答
  •  猫巷女王i
    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;
    }
    

提交回复
热议问题