Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'0' as a string with empty() in PHP

I want a 0 to be considered as an integer and a '0' to be considered as a string, but empty() considers the '0' as a string in the example below,

$var = '0';  // Evaluates to true because $var is empty if (empty($var)) {     echo '$var is empty'; } 

How can I 'make' empty() to take '0's as strings?

like image 614
Run Avatar asked Nov 09 '10 22:11

Run


People also ask

Does 0 count as empty PHP?

The following things are considered to be empty: "" (an empty string) 0 (0 as an integer) 0.0 (0 as a float)

Is an empty string 0?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.

What is empty string in PHP?

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. 0.0.

Does PHP empty check empty string?

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.


2 Answers

You cannot make empty() take it. That is how it was designed. Instead you can write an and statement to test:

if (empty($var) && $var !== '0') {     echo $var . ' is empty'; } 

You could use isset, unless of course, you want it to turn away the other empties that empty checks for.

like image 75
Jim Avatar answered Sep 21 '22 03:09

Jim


You cannot with empty. From the PHP Manual:

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

You have to add an additional other check.

like image 36
Gordon Avatar answered Sep 17 '22 03:09

Gordon