0

I keep getting " Notice: Undefined offset" for this code

<?php
    // Detect the subdirectory of the page
    $pagePath = getcwd();
    $pageDirs = explode("/", $pagePath);

    $currentDir = $pageDirs[sizeof($pageDirs)-1];
    $isHome = false;
    $subDir = null;

    if ($currentDir != "public" && $currentDir != "components" && $currentDir != "prototypes" && $currentDir != "styleguide"){
        // 2 levels deep in a Pages directory
        // Save the last 2 levels into vars
        $subDir = $currentDir;
        $currentDir = $pageDirs[sizeof($pageDirs)-2];
    }

    $hostname = getenv('HTTP_HOST');

    if ($currentDir == "legacy" || $_SERVER["PHP_SELF"] == "/coronita/index.php"){
        // This is the home index page
        // No subnav will be needed
        $isHome = true;
        $currentDir = "overview";

    }
?>

the error occur at this line

$currentDir = $pageDirs[sizeof($pageDirs)-2];

Any ideas? This code shows no errors on a mac but on my windows machine I get the error.

  • 3
    if the array's only got 1 element, then you're doing `$pageDirs[-1]`, and you cannot have negative array indexes. So start debugging: `var_dump($pageDirs)` and see what's in there at the time you get the error. And note that you're getting `undefined OFFSET`, which means `$pageDirs` is a string at that point, not an array. – Marc B Jul 25 '16 at 21:06

1 Answers1

0

That's because on windows you probably have your server on C:\public_html, on Mac it probably is in /Users/YOU/public_html. When you explode the path in windows it gives you an array with just 1 element, the very same path because there is no '/'. When you run it on Mac it returns an array with 3 elements.
So when you are in Mac the index sizeof($pagesDir) is greater than 2 and in windows lower than 2 so it throws an error because of the negative index.
This answer may be wrong, I don't know how you manage your files or where your page root is but I think this is the most probable answer.