List and explosion

I am trying to use URL rewriting on my website, and I want to use functions list()and explode()to get the right content. Currently my code is as follows:

list($dir, $act) = explode('/',$url);

In this case, it $urlis equal to everything after the first slash in the absolute URL, i.e. http://example.com/random/stuff => $url = random/stuff/this will work fine, but if I want to go to http://example.com/random/, then it will print a notification on the page. How to turn off the notification, do I need to use something different from the function list()?

Currently the notification is "Notification: Undefined offset: 1 ..."

Thanks for the help!

+3
source share
8 answers

You should check how many path segments the URL contains:

$segments = explode('/', $url);
if (count($segments) !== 2) {
    // error
} else {
    list($dir, $act) = $segments;
}

But perhaps you should choose a more flexible approach than using list.

+8
source

Try the following:

list($dir, $act) = array_pad(explode('/',$url), 2, '');

array_padfill an array with your values: ''.

+12
source
+4

, , , - , , explode URL-.

list , , =...
, explode .


, - :

$parts = explode('/', $url);
if (isset($parts[0])) {
  $dir = $parts[0];
  if (isset($parts[1])) {
    $act = $parts[1];
  }
}

, , $dir / $act , script.


, , (, /); .

+1

:

list($dir, $act) = explode('/',$url);

, , :

$segments = explode ('/', $url);
$dir = array_shift ($segments);
$act = array_shift ($segments);

, $act null,

+1

, URL-, $_SERVER['PATH_INFO'], "/random" script.

0

The simple and ugly answer is to prefix the whole thing with one "@", which suppresses error outputs. $ act will be set to zero in this case, because under the hood this is equivalent:

$foo = explode('/',$url);
$dir = $foo[0];
$act = $foo[1]; // This is where the notice comes from
0
source

The correct way to suppress E_NOTICE when assigning a list with PHP 5.4+ is as follows:

@list($dir, $act) = explode('/', $url);

If $urlnot /, explode will return one element, but $actwill NULL.

0
source

Source: https://habr.com/ru/post/1734923/


All Articles