Home > database >  Undefined offset: 1 explode
Undefined offset: 1 explode

Time:02-22

I was asked to fix the problems of an old project. I'm in stupor

$cabinetRoute = count($parts = explode('.', $host = $_SERVER['SERVER_NAME'])) < 3 ?
                               $parts[0].'.'.$parts[1] :
                               $host == '127.0.0.1' ? null : $host);

The error:

ErrorException (E_ERROR) Undefined offset: 1 (View: C:\OpenServer\domains\barterclub\resources\views\layouts\home.blade.php) (View: C:\OpenServer\domains\barterclub\resources\views\layouts\home.blade.php)

enter image description here

CodePudding user response:

Your code doesn't account for the possibility that $parts will only have one element.

Here's a re-write to deal with that, and also the logic is re-written for clarity, to avoid multiple nested ternary operators and functions which rapidly become hard to understand and even harder to debug.

As an aside, programming isn't a competition to fit everything into one line! Creating readable, testable and maintainable code is generally much more useful than writing the least number of lines technically possible.

$parts = explode('.', $host = $_SERVER['SERVER_NAME'])
$ct = count($parts);

if ($ct == 1) $cabinetRoute = $parts[0];
else if ($ct == 2) $cabinetRoute = $parts[0].'.'.$parts[1];
else $cabinetRoute = ($host == '127.0.0.1' ? null : $host);

CodePudding user response:

if(isset($parts[1])){
     $cabinetRoute =  count($parts = explode('.', $host = $_SERVER['SERVER_NAME'])) < 3 ? $parts[0].'.'.$parts[1] : ($host == '127.0.0.1' ? null : $host);
} else {
     $cabinetRoute = $_SERVER['SERVER_NAME'];
}
  • Related