1

I'm working on a project where I assign my URI list to a constant array.

$vars = explode("/", $_SERVER['REQUEST_URI']);
array_shift($vars);
if(end($vars) == "" && count($vars) > 0){ //remove last element when empty (occures when using / at the end of URL)
    array_pop($vars);
}
define("URI_VARS", $vars);
unset($vars);

The big question is, how can I check if an item exists? If I use defined("URI_VARS"), it of course works, but how can I check for instance does URI_VARS[1] exist?

defined("URI_VARS[1]") seems not to work. I found something online about defined("URI_VARS", "1") or defined("URI_VARS" , 1) but both are not working.

Thanks for the help!

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • `defined("URI_VARS") or define("URI_VARS", $vars);` will check if is defined, if not, define with `$vars`. Is that what you want? – Felippe Duarte Oct 22 '18 at 21:54
  • If you remove leading and trailing `/` using `trim($_SERVER['REQUEST_URI'], '/')`, you won't need your `if` block. – fubar Oct 22 '18 at 22:08

2 Answers2

2

defined() only takes one argument, so defined("URI_VARS" , 1) isn't a valid call. You'll get a warning and it will return null instead of true or false. You just need to add a second check to verify that the key exists after checking that the constant is defined.

$check = defined("URI_VARS") && array_key_exists(1, URI_VARS);

The second part (array_key_exists(1, URI_VARS)) won't be evaluated if the first part returns false, so you don't need to worry about undefined constant warnings.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

As @Don't Panic mentioned, you can use array_key_exists to check for the existence of the key you're looking for. If you don't know the specific key, or just want to check to see if you have a certain amount of URI segments, you could use count http://php.net/manual/en/function.count.php

if (defined('URI_VARS') && count(URI_VARS) >= 2) {
   // do something
}

Also, be careful about declaring an constants as an array, as the behavior has changed over time. PHP Constants Containing Arrays?

colefner
  • 1,812
  • 1
  • 16
  • 11