If I set a constant to = ''
,
How to I check if constant has something inside ?
(ie see if it is set to something other than the empty string.)
defined()
does not do what I want, because it is already defined (as ''
).isset()
does not work with constants.
Is there any simple way ?
Checking if a PHP Constant is Defined This can be achieved using the PHP defined() function. The defined() function takes the name of the constant to be checked as an argument and returns a value of true or false to indicate whether that constant exists.
The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
empty() function in PHP ? The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.
The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
The manual says, that isset()
returns whether a "[...] variable is set and is not NULL".
Constants aren't variables, so you can't check them. You might try this, though:
define('FOO', 1);
if (defined('FOO') && 1 == FOO) {
// ....
}
So when your constant is defined as an empty string, you'll first have to check, if it's actually defined
and then check for its value ('' == MY_CONSTANT
).
for checking if something is inside you can use (since PHP 5.5) the empty function. to avoid errors I would also check if it is even existing.
if(defined('FOO')&&!empty(FOO)) {
//we have something in here.
}
since empty also evaluates most false
-like expressions (like '0', 0 and other stuff see http://php.net/manual/de/function.empty.php for more) as 'empty'
you can try:
if(defined('FOO') && FOO ) {
//we have something in here.
}
this should work maybe with more versions (probably everywhere where you can get yoda conditions to run)
for a more strict check you could do:
if(defined('FOO') && FOO !== '') {
//we have something in here.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With