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!
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.
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.