daq Posted April 20, 2009 Share Posted April 20, 2009 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. Quote Link to comment Share on other sites More sharing options...
soak Posted April 20, 2009 Share Posted April 20, 2009 Could you use foreach() instead? That way it will just loop the values in your array, no need to check for bounds. Quote Link to comment Share on other sites More sharing options...
daq Posted April 20, 2009 Author Share Posted April 20, 2009 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. Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted April 20, 2009 Share Posted April 20, 2009 You could do // increment c $c++; // now check if $c needs resetting $c = (isset($arr[$c])) ? $c : 0; Quote Link to comment Share on other sites More sharing options...
daq Posted April 20, 2009 Author Share Posted April 20, 2009 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; Quote Link to comment Share on other sites More sharing options...
daq Posted April 21, 2009 Author Share Posted April 21, 2009 I put the increment in the wrong place, it was supposed to be $c = (isset(content[++$c])) ? $c : 0 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.