PHP is a weakly-typed language. By that I mean that variables are assigned values without regard to variable type, and implicit conversion at runtime sorts out any conflicts. PHP will happily let you compare a string and an integer, and if the string contains something unexpected, well, you should have paid more attention to data validation.
Given that the most important feature of PHP is the shallow learning curve, and that it is deployed in an environment where everything is a string, it’s (just) possible to argue that this was a good design decision. It allows you to do things like this:
$n = "5";
echo 3 + $n;
without getting into lots of tiresome explicit conversion. But the implicit rules are sometimes a little too clever for their own good, and throw up oddities like this:
$a = 'string';
$b = 0;
if ( $a == true && $b == false && $a == $b )
{
echo ( 'universe broken' );
}
What’s going on here? Lets look at these three clauses in detail:
( 'string' == true )because any non-null string evaluates totruewhen compared with a boolean( 0 == false )because the integer0undergoes implicit conversion to boolean and evaluates tofalse- Finally,
( 'string' == 0 )because a string is silently promoted to integer when compared with an integer. If the string is the ASCII representation of a number (eg"123"), it is assigned that value. If it doesn’t contain a number, it is assigned the value 0. So our third clause evaluates astrue. Oops…
I routinely use the triple-equals operator (identical) instead of the double-equals operator (equality) now, but it feels and looks like a hack to avoid someone else’s bad design decision biting me. PHP is chock-full of these little oddities.
If you want all the gory details, the type comparison tables are tucked deep inside the PHP Manual.
Update: This post over at ycombinator contains an excellent one-line summary of what I was getting at.
Tags: php
-
Pingback from AOWS » true == false on August 7, 2008 at 10:09 pm
-
Pingback from php to python. Why? | jodhpuriGuy | Avi Mehta on August 8, 2008 at 5:28 am
-
Pingback from PHP: true == false | Bao's blog on August 9, 2008 at 9:43 am
-
Pingback from Link Post Sunday 08/10 | Mr Sun Studios on August 10, 2008 at 5:01 pm
-
I think that oddity mentioned before is an small concession despite of the fast development you won. That’s the power of scripting languages.
BTW I’m a Java Developer, when I need speed I go for groovy.
-
Small Remark: “any non-null string evaluates to true when compared with a boolean” is not exactly true, the string ‘0′ also evaluates to false. I think this is a hardcoded exception not due to integer conversion, because the string ‘0.0′ evaluates to true.
-
Following “johnjo” comment: Don’t you people think it’s a bit sad that people in the industry start looking at PHP and ASP and even actionscript as a programming language rather than a script?!
I heard a while ago from someone that in his company they look at C++ as a low level programming language!
I think that in 10 years from now there will be such a few people that will know C/C++/ASM that we will have super computers, but they will run like 80286 because the OS will be written in ActionScript It starts happening today – not kidding! we have super computers that run a bit slow because too much code that should be written efficiently is written in .NET or Java, meaning using interpreters, meaning losing of efficency!
Anyway, I’m really waiting to the day that drivers programmer will get huge salary because there will be 10 of those in the world! ;-)
-
CPP, you are being sensationalist. The faster computers get, the more can be done in the background to help development. If you had to code in Assembly language today, we would have really fast, really memory efficient, BROKEN programs. Programming is a battle between the human mind, and the program’s complexity. With languages like .NET, Java, PHP, Python, etc., you are reducing the human brain’s requirement for complexity and trading off a (relatively slight) performance hit. I will take that tradeoff any day.
-
… that is why we have strict comparisons with === and !==
-
Pingback from Link Flood - 09/11/2008 | 1337hax0r.com on December 8, 2008 at 9:53 pm
-
Nick – this doesn’t make PHP a weakly typed language any more than having the symptoms of influenza gives you the flu. PHP *is* weakly typed (it’s often referred to as duck-typed – if it quacks like a duck, it’s probably a duck) – this is just a symptom of that.
Maybe you are inferring that the word “weakly” infers this is a bad thing, whereas it doesn’t, it’s just the name for this kind of typing. -
I searched Google for php “true == false” and found your post.
The reason was, today I ran into the same example as you did. But in my case, I think it’s even funnier/more stupid.
Just assign $a = ‘00′ and $b = ‘0′. The same conditions apply to these values, and the universe is broken again.
Why in the world do two different strings evaluate to be the same? Who knows.
-
=== to the rescue… I have been using it more and more. But in my opinion the whole language is a mess and should get a big overhaul. Just have a look at these different kinds of constructs which can, in some situations, do the same or worse have completely unexpected behavior:
if (isset($a)) …
if (is_null($a)) …
if ($a == null) …
if ($a === null) …
if ($a) …
if (!!$a) … -
When something as basic as comparisons do not function as expected, this is a serious problem and it is a problem that hackers are exploiting RIGHT NOW. Programmers aren’t lazy, they want a consistent programming environment. Many are coming from strict languages like C/C++. An expression like (‘1a’ == 1) should not evaluate as true. Loose typing would mean that (‘1′ == 1) evaluates as true, but PHP tries too hard to make an expression work and the === convention is an oddity (meaning any programmer with real experience is going to be unfamiliar with it). Weak typing is fine, but fundamental operations, such as comparisons, should work in a consistent and predictable way if we’re going to get serious about building secure web apps.
-
IMHO opinion, the case presented in this article is not an “oops!”, but a feature of the language. Also, I don’t see PHP as a weakly-typed language; it is a flexibly-typed language. The conversions are executed according to a set of rules, mostly very intuitive, which saves a lot of time and allows for quick functional code. It is the job of the developer to understand the on-the-fly conversions, just as much as strongly-typed languages demand an understanding of the types and the conversion functions.
Consider this example:
A formatting function. It accepts any value and returns it formatted:(…)
//returns any value formatted as a simple YES or NO representation
//compare to simple boolean and mysql null date
if ($value and substr($value, 0, 5)!= ‘0000-’) {
$result = ‘YES’;
} else {
$result = ‘NO’;
}This code analyses any value of any type and returns a simple YES or NO. For instance, we can store the date in which an action took place, but we only want to show the user IF it did take place. The same would apply to storing an id, a user name, a boolean true, or a simple 1. The only value that doesn’t evaluate properly is a mysql null date (bunch of 0’s as string), so we check for that separately.
This same function coded in your average strongly-typed language would take two pages of code.
I believe it is more about a personal preference in coding style than anything else. I’ve been programming for about 12 years (C/++/#, Java, ASP, Fox, Pascal/Delphi, etc), and to me strong-typing is a formality that often comes in as part of a generally more cumbersome approach to programming. Since I became acquainted with PHP some 7 years ago, it has been very hard to look back, and I’ve found myself missing nothing from the more bureaucratic languages, nor running into any difficulties beyond what would be expected during the course of a normal programming session.
-
I believe my opinion is more important than yours… blah blah blah.
PHP is a tool. If you don’t like it, use something else. The world is full of whiners… -
yes PHP is a tool but a too loosley typed tool.
function loose(string $string){
// do something with string
}
read the error fatal error function string expects type string. string given
god forbid it’s a tiny bit like c++
so now it
function string($string){
if(is_string($string)){
//bullshit
}
} -
perl does the exact same thing…
my $a=”string”;
my $b=0;
if ( $a == true && $b == false && $a == $b ) { print “universe broken”;}were you to compare bool($a) == bool($b), btw, you would get the expected result.
23 comments
Comments feed for this article
Trackback link: http://www.otton.org/2008/08/06/stupid-php-tricks-true-false-comparison/trackback/