Mixing Conditions and Assignments

Here is another tip from "Mistakes I've Made". Don't mix up your conditions and assignments. In other words be careful about using assignment operators (like the eqauls sign '=') inside of conditional statements. Although this happened with PHP, the same problem can occur with many other languages. Let me explain...

Here is a very common way to loop:

<?php
while ($data = mysql_fetch_array($result)) {
 
// do stuff with $data...
}
?>

I was debugging a problem inside of this loop. While I was doing this, I wanted to break the loop early. So this is what I wrote:

<?php
$stop
= 0;
while (
$data = mysql_fetch_array($result) && $stop++ < 50) {
 
// do stuff with $data...
}
?>

As soon as I changed this code, everything inside the loop that dealt with $data stopped working. Can you see why?

I had forgotten about operator precedence. If you look at the table on the documentation for PHP operators, you will see that the logical AND ('&&') has a higher precedence than the equals sign. This means that the line was not evaluated in left to right order like I was expecting. Instead the first thing that was evaluated was this:

<?php
mysql_fetch_array
($result) && $stop++ < 50
?>

Which evaluated to either true or false. Then that value was assigned to $data:

<?php
$data
= true
?>

So when I tried to treat $data like the array I was expecting I immediately ran into problems. Of course, part of the problem is that PHP is a loosely typed language. That means that it didn't care if $data was an array or a boolean. I'll be the first to admit that I take advantage of this, but it is times like these when I regret not being forced to declare my variables and their types, and to do conversion by hand like I did in the good old days.

Anway, here is one method for doing what I wanted:

<?php
$stop
= 0;
while ((
$data = mysql_fetch_array($result)) && $stop++ < 50) {
 
// do stuff with $data...
}
?>

As you can see I have added parentheses which make my intent clear. Next time I will remember to watch out when mixing conditions and assignments, and I hope this article helps you remember too.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.