Jump to content

[SOLVED] Array index out of bounds


daq

Recommended Posts

Couple of questions about arrays:

1. Does array value with index out of bounds always return NULL or is there a chance it will return garbage? I.e.:

$myArr ("one", "two");
echo "Value of " . $myArr[5];

 

2. I'm iterating through an array throughout a large chunk of code with a basic array[$c++]. What's the best way to monitor index without reinventing the wheel? I was hoping to be able to catch an out of bounds exception to reset the index ($c) to 0, but it doesn't throw one.

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/154903-solved-array-index-out-of-bounds/
Share on other sites

Could you use foreach() instead? That way it will just loop the values in your array, no need to check for bounds.

 

Array is not used in a loop, but in various places throughout the code. The code goes through approximately 4-7 $c increments during the run.

 

To clarify, loop does not iterate the array, but rather pulls incremental values from it when it needs them. I just need a way to reset the index when it goes out of bounds.

You could do

 

// increment c
$c++;

// now check if $c needs resetting
$c = (isset($arr[$c])) ? $c : 0;

 

The disadvantage of this way is that I will have to check before each use. With something like a try catch, I would only have to write code that handles out of bounds once.

But this is a great suggestions if nothing like try catch is available.

 

Even shorter:

$c = (isset($arr[$c])) ? $C++ : 0;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.