Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

topvillas's avatar

Casting a String to a Boolean in an Elegant Way?

I must have done this a million times but today it's started to bother me.

Is there a more elegant way to accomplish this. Casting to boolean clearly doesn't work because a non empty string is true.

$cascade = Request::get('cascade', 'true');
$cascade = $cascade == 'true' ? true : false;
0 likes
5 replies
Cronix's avatar

instead of true/false, I use numbers, which can be cast to bool

(bool)"1" //true
(bool)"0" //false

$cascade = (bool)Request::get('cascade', '1');
crnkovic's avatar

If cascade from the input must be 'true' or 'false' (string literal) (which it probably doesn't, there are many ways to escape this), $castedToBoolean = $cascade === 'true'; should be enough.

Cronix's avatar
Cronix
Best Answer
Level 67

Another thing you could do is just not include the cascade param if the option is false, only add it if it's true. Then you could just see if the request has it.

$cascade = Request::has('cascade'); // true/false
topvillas's avatar

That would work but I'm passing it in a query string as part of an API. So I wanted to make the value nice and clean.

In the end I created a str_bool helper function (which is pretty ugly). But it keeps my controller code a bit cleaner and less blurgh!

Please or to participate in this conversation.