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.
Related Topics
Lazarus: Program without GUI - Many WSRegister Errors
Question | 6 Answers
Filelist Creator: How to print a List of Files
Info | 0 Comments
Delphi: System-Wide HotKey
Tutorial | 1 Comment
JavaScript: Create and Use Arrays
Info | 0 Comments
Send form input as an array to PHP script
Tip | 0 Comments
Delphi/Lazarus: Is the ALT, SHIFT or CTRL key pressed?
Tutorial | 0 Comments
PHP: Remove all empty elements from string array
Tip | 0 Comments
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.
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:
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:
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