Daryl Gill
Daryl Gill

Reputation: 5524

Check constant is defined but empty?

<?php
    define ('foo','');
if (defined('foo')){
    if (empty(foo)){
        echo "Notice: Foo Is Defined, But Does Not Carry A Value. Please Set It";
    }
}

If have this current script, I am running a set of checks on defined constants which the user needs to define in the configuration page.. The problem is, the config gets shipped out with nothing defined:

define ('foo','');

and when running the script, I first check that the necessary constants are correctly defined and do carry a value.

The problem is, that I can get if the value is defined, but I cannot correctly check if it's empty.

I know with empty expects a variable passed, if i pass my defined constants into a variable, doesn't it kinda defeat the point?

<?php
 define ('Foo','');
 $Foo = Foo;
 if (empty($Foo)){
  echo "Foo Is Empty"; 
}
?>

Whereas I might aswell setup:

$Foo = 'Value';
$OtherConstant = 'Another';

so how can I check whether my constant is carrying a value when that is defined?

Upvotes: 1

Views: 6737

Answers (1)

user1655741
user1655741

Reputation:

You could simply do that:

if (defined('foo')) {
    echo 'defined';
    if (foo) {
        echo 'not empty';
    }
    else {
        echo 'empty';
    }
}
else {
    echo 'not defined';
}

If foo is an empty string the if(foo) conditional will evaluate false. There are subtle differences between empty() and converting to boolean. Please refer to the PHP manual for other cases. Boolean conversion, empty()

Upvotes: 5

Related Questions