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
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.

Link to comment
Share on other sites

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;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.