00 Votes

Print current and next Value of Array - Undefined Array Key Error

Question by Guest | 2022-07-30 at 12:16

I have the following PHP code:

$var = array(2, 5);
$cnt = count($var);

for ($i = 0; $i < $cnt; $i++) {
   echo $var[$i]."\n";
   echo $var[$i+1]."\n";
}

However, the code shows this error:

(!) Warning: Undefined array key 2 in 
C:\xampp\htdocs\CAYTASOURCE\snippets\q.php on line 7

I want to print the current and next array value.

ReplyPositiveNegative
-11 Vote

The problem with your code is as follows: You have an array with two elements (indexes 0 and 1). Then you loop through this array with $i < number of array elements. That means in the loop, $i takes the values 0 and 1. This is no problem for $var[$i] (0 and 1 are in the array range), but for $var[$i+1] (1 in but 2 not in the array range).

So, you have to possibilities:

for ($i = 0; $i < $cnt - 1; $i++) {
   echo $var[$i]."\n";
   echo $var[$i+1]."\n";
}

Here we use $cnt - 1 so that also $var[$i+1] has no change to get out of the index range of the array.

Or we can go like that:

for ($i = 0; $i < $cnt; $i++) {
   echo $var[$i]."\n";
}

Here we are using no $i+1 so that we are again always in the index range also without $cnt - 1.
2022-07-30 at 16:48

ReplyPositive Negative
Reply

Related Topics

Delphi: System-Wide HotKey

Tutorial | 1 Comment

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.