6
myss
6d

PHP are you freaking kidding me right now? Why are you forcing me to write ugly and meaningless code like this?

Today I just learned that boolval("false") will return true.

I'd deffo expect this from casting operators, but not from a function which even has val inside of its name.

What purpose is to have functions like these in language if they just serve as plain wrapper for casting operators

Comments
  • 3
    Php: the one language you have a magnitude of ways of doing the same thing - because reasons.
  • 6
    and in which language exactly is the boolean value of a non empty string not true?
  • 3
    @C0D4 Different ways for different people!

    "What kind of PHP Dev are you? Find out with these quick questions!"
  • 0
    @erroronline1 in the same one which returns false for boolval("0")
  • 3
    @myss because 0 is falsey.

    @Jilano the kind that's seen way to many things to not get surprised anymore.
  • 5
    @myss welcome to dynamically typed languages where puking out programs is faster but debugging becomes harder.

    In your case, if you expect the value to be (string) "true" or "false", then the best practise would be to use

    $dataValue = $dataValue === "true";

    If you accept all kinds of value types for $dataValue beforehand, then I'd say it's a mess.
    Chances are you use PHP 7+ which comes with type-hinting. If $dataValue is a function parameter, you can decorate it with a type so PHP will throw an exeption on invalid function call.
    When you get $dataValue from some user input, then you should do validation there.
  • 1
    @myss i see... was not aware of this. my apologies.
  • 0
    @myss You can always use json_decode as a one liner. Sure it's not fast but it parses all of the cases for truthy / falsy result 😁
  • 1
    @erroronline1 don't apologise. Many have fallen in this trap hole.

    Btw. don't use boolval / intval and so on.

    (int)
    (bool)
    ...
    are ur friend.
Add Comment