I am trying to build up a script that gets the current percentage of the iteration of a loop.
I have :
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.
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
}
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;
}
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;
}
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 ));
}