How to fix undefined offsets

I have a php notice stating undefined offset:1 on line 5 (in this example).

 1   private function checkForActiveControllerAndAction($filename, $navigation_controller_and_action) {
 2       
 3       $splitted_filename = explode("/", $filename);
 4       $active_controller = $splitted_filename[0];
 5       $active_action = $splitted_filename[1];
 6       $splitted_filename = explode("/", $navigation_controller_and_action);
 7       $navigation_controller = $splitted_filename[0];
 8       $navigation_action = $splitted_filename[1];        
 9       if ($active_controller == $navigation_controller AND $active_action == $navigation_action) {
 10           return true;
 11       } else {
 12           return false;
 13       }
 14   }  

What's causing it and how can I prevent this?

Answers


When you explode the $filename the string may not contain a / character, which means the whole of $filename will remain in the first element of the array (by default).

You should check the length of the array count or check if the element exists isset.

This is what causes the unknown offset error.

Readup on explode here: http://uk1.php.net/explode

To check if you can access the 2nd index:

if (isset($splitted_filename[1])) {
    // Code
}

Need Your Help

Unit Testing with ExpressJS

javascript node.js unit-testing express mocha

I am trying to unit test my ExpressJS routes. It looks something like this

Trying to resize a UITableView glitches the screen for a second before displaying properly

iphone ios uitableview uiview uinavigationbar

I had a lot of trouble resizing a UITableView to fit between an UINavigationBar and a UITabBar. My implementation involved creating a custom frame in viewDidAppear(), and then setting the UITableVi...