jim
jim

Reputation: 141

Checking if a constant is empty

Why is this not possible?

if(!empty( _MY_CONST)){
  ...

But yet this is:

$my_const = _MY_CONST;
if(!empty($my_const)){
  ...

define( 'QUOTA_MSG' , '' ); // There is currently no message to show

$message = QUOTA_MSG;
if(!empty($message)){
  echo $message;
}

I just wanted to make it a little cleaner by just referencing the constant itself.

Upvotes: 13

Views: 9216

Answers (6)

slava
slava

Reputation: 837

If constant defined and need check is empty or not, for example you use it in config file, you can use !MY_CONST:

define('MY_CONST', '');
if (!MY_CONST) {
    echo 'MY_CONST is empty';
}

Upvotes: 0

Mr Griever
Mr Griever

Reputation: 4023

if (!empty(constant('MY_CONST')) {
    ...
}

mixed constant ( string $name )

Return the value of the constant indicated by $name, or NULL if the constant is not defined

http://php.net/manual/en/function.constant.php

Upvotes: 3

Nabil Kadimi
Nabil Kadimi

Reputation: 10384

You can get along with this if for some reason you are still not using PHP 5.5.

if (defined('MY_CONST') && MY_CONST) {
    echo 'OK';
}

Upvotes: 7

what about strlen?

if(strlen(MY_CONST) == 0) 

Upvotes: 2

Arthur
Arthur

Reputation: 3797

Just letting you know that you can do

if(!empty(MY_CONST))

since PHP 5.5.

Upvotes: 13

Pekka
Pekka

Reputation: 449395

See the manual: empty() is a language construct, not a function.

empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).

So you'll have to use a variable - empty() is really what you want in the first place? It would return true when the constant's value is "0" for example.

Maybe you need to test for the existence of the constant using defined() instead?

Upvotes: 17

Related Questions