Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistency between TRUE and FALSE constant definitions in PHP

Tags:

php

casting

Sometimes I bang my head into the wall, because of this.

var_dump(ord(true), ord(false));

gives:

int(49)
int(0)

So TRUE is converted into ASCII code 49 - number 1, and FALSE to ASCII code 0 (zero byte). Why such inconsistency in TRUE/FALSE conversions into a string? Why FALSE can't be converted into ASCII code 48 - number 0 where integer context is expected (because TRUE is '1')?

The biggest problem from such definitions is that if you store Boolean values in some variables which you later save in the database - then TRUE is stored as '1' and FALSE as '' - an empty string. So before storing in database you need to cast to integer (int)($bool_variable). Given that PHP supports full automatic type-casting, the need to perform a manual casting in some scenario(s) is very frustrating and a bit stupid (either ALL types should be interchangeable or user must perform casting itself between all types).

Any ideas?

like image 880
Agnius Vasiliauskas Avatar asked Dec 09 '25 09:12

Agnius Vasiliauskas


1 Answers

It inherently doesn't make sense to ask for the ord of a bool. ord expects a string, so casts any input to a string. true casts to '1', and false casts to ''. The ord of '1' is 49, and the ord of an empty string is 0.

That doesn't mean that true and false are defined as such. true is defined as true and false is defined as false. It's merely the type casting rules that you're stumbling over (and yes, they're arguably arcane). Most databases support native boolean types, or their PHP database API will convert PHP booleans to the database's equivalent, as long as you use the API correctly.

As for why those casting rules exist:

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

https://www.php.net/manual/en/language.types.string.php#language.types.string.casting

No, it doesn't make any more sense than this.

like image 83
deceze Avatar answered Dec 11 '25 00:12

deceze



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!