Understanding the difference between single equal sign (=), double equal sign (==), and triple equal sign (===) operators in PHP

Posted on 24. Jul, 2010 by Matt Borja in Web Development

I was looking around just a few minutes to refresh my memory on what the difference was between the double equal sign comparison operator and triple equal sign comparison operator only to end up leaving a couple comments with further clarifications on the topic itself. Here is one of them that I believe sums it up about as beginner and user friendly as it can possibly be:

Always remember (at least in PHP) that the data type of a variable is being set automatically by the type of value you assign it. This could be integer (int), floating point (float), associative array (array), boolean (bool), class object (object) or even a resource, in which case the variable would be of a resource data type (e.g. a simple MySQL query).

Use of the triple equal sign (===) for comparison is most appropriate when data types matter. However, you find yourself rarely using this if you force data types by typecasting input variables (especially user input). For example:

function get_user_profile($user_id) {
$user_id = (int)$user_id;
echo '<p>Retrieving user profile for User ID #', $user_id, '</p>';

// $sql = mysql_query(“SELECT * FROM users WHERE user_id={$user_id} LIMIT 1″) or die(mysql_error());
// and so on…
}

In this particular case, you can see that typecasting is going to force that $user_id to be of integer (int) data type and anything you specify in the accept_input() function will be treated as an integer. Default in most cases it comes out to 0 but there are a lot of fun on-the-fly sanitization tricks you can do like this to cut out the extra if/then statements.

Tags: , , , , ,

One Response to “Understanding the difference between single equal sign (=), double equal sign (==), and triple equal sign (===) operators in PHP”

  1. Matt Borja

    05. Sep, 2010

    Hello, world!

    Reply to this comment

Leave a Reply