Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a constant is empty

Tags:

php

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.

like image 693
jim Avatar asked May 31 '11 11:05

jim


People also ask

Is 0 considered empty?

"0" is considered as no value or empty value.

How to check if an Object is empty in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

How to check empty String PHP?

We can use empty() function to check whether a string is empty or not. The function is used to check whether the string is empty or not. It will return true if the string is empty. Parameter: Variable to check whether it is empty or not.

Why is variable empty?

A variable is considered empty if it does not exist or if its value equals false .


2 Answers

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

like image 193
Mr Griever Avatar answered Oct 05 '22 23:10

Mr Griever


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?

like image 22
Pekka Avatar answered Oct 05 '22 23:10

Pekka