Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why empty('0') = true; empty('00') = false;

Tags:

php

I eval $var using

if(empty($_GET['var'])){
    ...
    }

I take TRUE from

https://myweb.com/?var=0

I take FALSE from

https://myweb.com/?var=00
like image 834
Stackoverflow Avatar asked Jul 23 '26 01:07

Stackoverflow


1 Answers

The empty pseudo-function shares its logic with casting to boolean - if something is equivalent to "false", it is considered "empty".

The list of values which are considered "empty" is intended to be helpful, but is occasionally confusing, because there isn't really one perfect answer. Starting off with integers, it seems reasonable that 0 is "empty", but for instance 1 is not. Because user input almost always comes in the form of strings (particularly on the web, where PHP is most at home), it's also useful for the string "0" to behave the same as the integer 0.

On the face of it, "00" should also be equivalent to 0, and therefore "empty", but now things start getting messy: if you convert the string "hello" to an integer, that is also 0, so is "hello" also empty? That wouldn't be very useful.

The truth is, casts such as this can only really work one of two ways:

  • Throw an error on any conversion which is not 100% unambiguous.
  • Pick a set of compromises which is mostly useful, but not entirely consistent.

PHP picked the second route, and the difference between empty("0") and empty("00") is one of the side effects of the particular compromise chosen. Other languages which took a similar route (e.g. Perl, JavaScript) have different compromises, with different surprising outcomes.

See also my answer to a similar question here.

like image 63
IMSoP Avatar answered Jul 25 '26 18:07

IMSoP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!