reading array values in a loop

Hello there:

function Calc($DDX, $II) {
global $DDX, $II;
print_r($DDX); // DDX[1][1][1]=12.34, DDX[2][1][1]=9.6435, …

      $J=1;
      $K=1;
     $ALL=0;
     for ($I=1;  $I<=$II; $I++) {

100: $ALL=$ALL+$DDX[$I][$J][$K];
}
}
when I run this function, I get “Undefined index: 1 in line 100”. However, by changing $DDX[$I][$J][$K] to for exapmle $DDX[3][1][1], I can get a new value for $ALL.
Would you please let me know why I do get error “Undefined index: 1 in line 100”?

Well, you are looping thru DDX using the first dimension from DDX[1]…to…DDX[$II]…
My guess is that $II is outside of the number of DDX’s there are…
If you have 3 entries in this array DDX[0], DDX[1], DDX[2] , then DDX[4] would fail.
(Also, remember ARRAY’s start at 0 not 1…)

To test this, echo (print) $i and DDX[$i][1][1]; at each addition step and see where it fails…

Hope that helps…

Expanding on ErnieAlex’s point, you may benefit from changing the loop to either of these methods:

[php]$max = $II > count($DDX) ? $II : count($DDX);
for ($I=1; $I<=$max; $I++) {
$ALL += $DDX[$I][$J][$K]; // $var += 1; is shorthand for $var = $var + 1;
}[/php]

or

[php]foreach($DDX as $val)
{
$ALL += $val[$J][$K];
}[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service