using array_sum() in a while loop
Posted
by m477
on Stack Overflow
See other posts from Stack Overflow
or by m477
Published on 2010-04-29T16:38:44Z
Indexed on
2010/04/29
16:47 UTC
Read the original article
Hit count: 382
php
|while-loops
Hi folks,
I'm learning PHP. Having trouble understanding why this piece of code isn't working.
In particular: why is the result of array_sum($x) (1596) greater than $cap? Perhaps I'm not understanding the nature of while loops, but it seems to me (looking at a print_r($x)), the loop should cut out a step before it actually does.
<?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
© Stack Overflow or respective owner