# Getting the percentage of current iteration completion in an array using numerical keys?

This has me banging my head against the desk either because I just suck as visualizing math issues or else because I’m in a hurry but I’m hoping some of you can help a guy through this…

I’m trying to calculate the current progress of iteration with an array that is comprised of numerical keys (the values of each element have nothing to do with this–I’m basing the calculation off of the keys only).

Example:
if \$array has 4 elements (i.e. - \$array[0], \$array[1], and so on), how might one return the “percentage progress” after each iteration of the array in a foreach loop?

(I.e. - after iterating past \$array[0], the percentage complete would be 25%, and then after iterating after \$array[1], it would be 50%, etc.)

Any insight into this likely trivial issue would be very appreciated.

How are you iterating? Foreach? While? For?

Is your array guaranteed to be continuous?

I’m using a foreach and yes, I’ll always have numerics for the keys, all in order, starting with 0 (zero).

foreach(\$var AS \$key => \$value) {
\$percent = ((\$key +1)/count(\$var)) * 100;
}
1 Like

Nailed it, StarLion. Thank you so much! I’ll sleep easier tonight thanks to you.

I’m curious, and it probably matters little, but I always do like

\$var_length = count(\$var);
foreach(\$var AS \$key => \$value) {
\$percent = ((\$key +1)/\$var_length) * 100;
}

to save from needing to do count() every iteration.
Trivial performance benefit?

2 Likes

Not trivial depending on the size of \$var. But the original post was more about the math involved than optimization of actual code.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.