ILovephp123 ILovephp123 - 7 months ago 25
PHP Question

Getting undefined offset in my PHP For loop

These are the errors I'm getting


( ! ) Notice: Undefined offset: 1 in C:\wamp64\www\searches.php on line 35
Call Stack

( ! ) Notice: Undefined offset: 2 in C:\wamp64\www\searches.php on line 35

( ! ) Notice: Undefined offset: 2 in C:\wamp64\www\searches.php on line 42


Line 35 is
$totalSum = $totalSum + $amYearNumbers[1][$x];


This is part of the whole for loop

preg_match_all('/(\d)\s<span>year/', $amItemYEAR, $amYearNumbers);
print_r($amYearNumbers);
if ($amYearNumbers) {
$amYearNumbersLength = count($amYearNumbers);
$totalSum = 0;
for ($x = 0; $x <= $amYearNumbersLength ; $x++) {
$totalSum = $totalSum + $amYearNumbers[1][$x];
}
}


print_r($amYearNumbers);
returns


Array ( [0] => Array ( [0] => 8 year ) [1] => Array ( [0] => 8 ) )


I'm sure what the error is exactly, I just want to add up all the numbers that are given back

Answer

Check this,

if (count($amYearNumbers)) {
    $amYearNumbersLength = count($amYearNumbers[0]);
    $totalSum = 0;
    for ($x = 0; $x < $amYearNumbersLength ; $x++) {
        $totalSum = $totalSum + $amYearNumbers[0][$x];
    }
}