in General, PHP, Ruby

Intricacies of PHP compared to Ruby

Via Tim Bray’s blog I found zestyping’s “Why PHP should never be taught”. In it he provides some interesting PHP code that will be difficult for beginners to understand.

$a = 0;
$b = "eggs";
$c = "spam";


a == b
b != c
a == c
a == d
b != d
c != d

(Please note that d hasn’t been defined). In the comments, people freak out and tell him that this behaviour is defined in the documentation. I guess that makes it even worse.

Trying the same thing in Ruby:

a = 0
b = "eggs"
c = "spam"

a == b
=> false

b == c
=> false

a == c
=> false

a == d
NameError: undefined local variable or method 'd' for main:Object from (irb):7
  1. If you want to do a comparison by type and value in PHP you should use === or !==. In that case it will act the same as Ruby. If you have notices turned on for PHP it will warn about $d not being defined if I remember correctly.

    The reason PHP does this is that it supports the usage of strings containing a numeric value as a numeric value. So if you have a string containing the number “3” you can multiply another number with the string. If a string starts with a number and after that contains some chars the number at the start of the string will be used. If it doesn’t start out with a number PHP will threat the string as if it’s the number 0.

    So yeah, you have to be aware of this behavior of PHP when programming in PHP but as you can see there are simple ways to avoid this “issue”.

  2. That is the reason I like POLS.

    Even if I program in PHP for a couple of years, this kind of behavior will always surprises me.

    Let me ask you about hexadecimal operations in PHP.

Comments are closed.