1

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;
}
?>
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • 1
    You can fill these empty lines with explanation about the code, what the expected output and the actual one, because I quite agree - This code is not readable to me too. Please [edit] your post and create a [mcve] – Alon Eitan Oct 13 '18 at 15:38

1 Answers1

0

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

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • thank you, but i didn't understand ($tri[$z] ?? 0), what's the function of "??" ? – user9188379 Oct 15 '18 at 20:09
  • The null coalescing operator (new to php 7+) is a succinct way to write `issest($tri[$z]) ? $tri[$z] : 0`. Effectively, if the element exists, use the element's value, if not use `0` as the fallback value. Here's another way without the null coalescing operator: https://3v4l.org/E23r7 – mickmackusa Oct 15 '18 at 20:46