2

So, I've written some rather convoluted 'functional' PHP code to perform folding on an array. Don't worry, I won't use it anywhere. The problem is, PHP's 'each' function only seems to go as far as the end of an array as it is statically (actually, see bottom) declared.

// declare some arrays to fold with
$six = array("_1_","_2_","_3_","_4_","_5_","_6_");

// note: $ns = range(0,100) won't work at all--lazy evaluation?
$ns = array(1,2,3,4,5,6,7,8);
$ns[8] = 9; // this item is included

// add ten more elements to $ns. each can't find these
for($i=0; $i<10; ++$i)
    $ns[] = $i;

// create a copy to see if it fixes 'each' problem
$ms = $ns;
$ms[0] = 3; // Just making sure it's actually a copy

$f   = function( $a, $b ) { return $a . $b; };
$pls = function( $a, $b ) { return $a + $b; };

function fold_tr( &$a, $f )
{
    $g = function ( $accum, &$a, $f ) use (&$g)
    {
        list($dummy,$n) = each($a);
        if($n)
        {
            return $g($f($accum,$n),$a,$f);
        }
        else
        {
            return $accum;
        }
    };
    reset($a);
    return $g( NULL, $a, $f );
}

echo "<p>".fold_tr( $six, $f  )."</p>"; // as expected: _1__2__3__4__5__6_
echo "<p>".fold_tr( $ns, $pls )."</p>"; // 45 = sum(1..9)
echo "<p>".fold_tr( $ms, $pls )."</p>"; // 47 = 3 + sum(2..9)

I honestly have no clue how each maintains its state; it seems vestigial at best, since there are better (non-magical) mechanisms in the language for iterating through a list, but does anyone know why it would register items added to an array using $a[$index] = value but not '$a[] = value`? Thanks in advance any insight on this behavior.

1 Answer 1

2

Your loop is exiting early thanks to PHP's weak typing:

if($n)
{
    return $g($f($accum,$n),$a,$f);
}
else
{
    return $accum;
}

when $n is 0 (e.g. $ns[9]), the condition will fail and your loop will terminate. Fix with the following:

if($n !== null)
Sign up to request clarification or add additional context in comments.

1 Comment

Doh! I wish I had realized that a few hours ago. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.