Search code examples
phparraysfor-loopnoticepascals-triangle

Pascal's triangle works but throws an Notices


Here is my script. The program can't find values in $tri array when I do $somma=$tri[$y]+$tri[$z];?

I keep getting Notices, but why?

<?php
$tri=array(1,1);
for ($x=0;$x<=6;$x++) {
    print_r($tri);
    $count=count($tri);
    $trinew=array();
    for($y=0;$y<$count;$y++) {
        $z=$y+1;
        $somma=$tri[$y]+$tri[$z];    // <-- here is the problem
        array_push($trinew,$somma);
    }
    array_unshift($trinew, 1);
    $tri=$trinew;
}
?>

Solution

  • When $y = $count - 1, then $z = $count and there is never an element available via $tri[$z].

    For example, on the first iteration of $x, $tri is:

    array (
      0 => 1,
      1 => 1,
    )
    

    When $y = 0 and $z = 1 everything is fine, but when the nested for() moves to its final iteration ($y = 1 and $z = 2), $tri doesn't have a 2 index.

    This is why you are receiving Notices.


    With a null coalescing operator and some other minor touches, this seems to run smoothly:

    Code: (Demo)

    $tri = [1, 1];
    for ($x = 0; $x <= 6; ++$x) {
        var_export($tri);
        $trinew = [1];
        for($y = 0, $count = count($tri); $y < $count; ++$y) {
            $z = $y + 1;
            $trinew[] = $tri[$y]  + ($tri[$z] ?? 0);
        }
        $tri = $trinew;
    }
    

    Or you could push a 0 element into $tri before the inner for loop and subtract 1 from the count(). https://3v4l.org/sWcrr