Software Engineering

PHP proper string to boolean casts

Casting a string to a boolean can be tricky but it’s actually super easy. First of all never use boolval or casts like (bool) $string. It will never work or won’t result in what you believe it will. There are good reasons why it’s like that and I’m aware that other languages cope that with ease.

Just use filter_var which can properly convert strings into booleans. filter_var can do a lot more, but for booleans I use it all the time. Also check out if your framework provides something cool, some does, some doesn’t.

Just a common mistake I’ve often seen. Cheers and have fun coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close