Using array_sum () in a while loop
I am learning PHP. I don't understand why this piece of code is not working.
In particular: why is array_sum ($ x) (1596) greater than $ cap? I may not understand the nature of while loops, but it seems to me (looking at print_r ($ x)) the loop should cut out a step before it does it.
<?php
function fibonacci_sum($cap = 1000){
list( $cur, $nxt, $seq ) = array( 0, 1, array() );
while ( array_sum($seq) < $cap ) {
$seq[] = $cur;
$add = $cur + $nxt;
$cur = $nxt;
$nxt = $add;
}
return $seq;
}
$x = fibonacci_sum();
echo array_sum($x);
?>
Any insight is appreciated.
Best, matt
a source to share
Look at it this way: if array_sum($x)
less $cap
, then the body of the while loop will be executed again. So when the while loop has stopped executing, by definition the condition at the top while
will be false. (*) I think you mean to say:
while ( array_sum($seq) + $cur < $cap ) {
This will stop just before you exceed $cap
what you seem to want to do.
(*) Yes, yes, no influence of expressions break
.
a source to share
Simple order of execution.
If you add a little variable observer, it will be easy for you to see how this happens.
while ( array_sum( $seq ) < $cap )
{
echo $cur, ' : ', array_sum( $seq ), '<br>';
$seq[] = $cur;
$add = $cur + $nxt;
$cur = $nxt;
$nxt = $add;
}
If you run this the last output shows 610 : 986
. So 986 is less than 1000, so the loop iterates, but the very first line of the loop clicks $cur
on $seq
anyway - completely oblivious to the fact that it just created a sum than a cap. So when you execute array_sum()
outside of a function, that 610 is part of it, hence 1596.
So what you really want is when the sum of the array plus the next value is less than the cap.
while ( array_sum( $seq ) + $cur < $cap )
But, it's a little strange that your function returns an array at all. Why not just return it directly?
a source to share