logo

Compare the right way

Add comment

When I was programming today I got into a small problem, which I quickly solved, but it gave me a very good idea for a tutorial. Namely, what happened to me? I worked on an easy loop through array with use of functions current and next. I created custom array with custom values, and when I started the code, I did not get what I’ve expected. This is an example of the code.

<?php
$array = array(
	1,
	0,
	2
);
do {
	echo current ( $array ), ', ';
} while ( next ( $array ) );
?>

As a result I was expecting “1, 0, 2, ” but I received only “1, “. I looked my code little better and I noticed that the error was causing line 9. Function next advances pointer of an array towards the end, thereby returning the value of key in which the cursor is shifted. As you can see, the loop is executed until the value is not “false.” But we have no “false” in our array. Why is function then disrupted? Answer is “type juggling”, process that PHP uses when comparing values. Namely, when PHP compares values, he converts them. Since we did not define with what we compare, PHP assumed that we wish that our loop goes until the next value from function is false.
Following code represents what PHP assumed

} while ( next ( $array ) == true );

When we use operator “==”, if variables are not the same type on both sides, PHP converts them from one type to another.
More information on type comparison and operators comparison.
As you can see, on one side we have “1″ and on the other one, “true”. Since the values are not the same type, PHP casts „1“ to „bool“. As a result you get “true == true”, condition is valid and we go into a new round. Now when we come to “0″ PHP converts it to “bool” and it becomes “false.” As a result we obtain “false == true”, which is not true, the condition is invalid and PHP gets out of the loop. This problem is solved by using identical operator “===”. While the equality operator checked whether the value is equal to, identical operator checks whether the values are the same type of data and also equal.
Line 9 now looks like this, and we get the result as we expect.

} while ( next ( $array ) !=== false );

My advice is to use “===” instead of “==”.
Now I have another example in which I would like to show you something. It happens often that the loops or conditions containg only function, but do not test its output.
Here’s what I mean.

if (function ()) (

)

not

if (function () operator, value) (

)

This is not good. It often causes bugs. As I said previously, PHP takes some values that he thinks are correct, and compares them.
Let us take for example the following code.

<?php
if ( $var = file_get_contents ( 'proba.php' ) ) {
	echo 'Success.';
}
else {
	echo 'Error.';
}
?>

Simple condition that, if it failes opening the file, prints “Error.”. In some situations, will open file successfully, but PHP will still print “Error.”. Suppose that the file is empty. PHP will load files content, store it in a variable and make a comparison. Since we have not defined with what will we compare reslult oft he function, PHP will again make a change of type data and the empty string will be casted to “false.” Because of this, we will get a notice that the opening was not done properly, even though it was. Likewise, if file contains “0″, we will get the same result. It is very easy to avoid that, if we set our conditoon properly.
If you want to save value to a variable, condition structure will be like this:

if ( ( $var = nekaFunkcija () ) operator, value) (

)

.

If you do not want to save value to a variable, condition will look like this:

if ( function () operator, value) (

)

.

The operator should bee “===” to match and “!==” not to match.
Value is the value that should (not) be functions output value.

If we apply this to our code, it will look like this:

if ( ( $var = file_get_contents ( 'proba.php' ) !== false ) {

.

Related Posts
  • 02.01.2010 — Enable E-mail In PHP – Win (0)
    This will be a quick tutorial that will show you how to enable e-mail function in PHP on Windows….
  • 16.10.2009 — PHP DomDocument Tutorial (5)
    This will be a quick tutorial that will show you how to use PHP’s DOMDocument to parse your XML so y…
  • 09.09.2009 — AJAX Multi-Level Comments (16)
    In this tutorial we will create multi level comments. You must have seen comments on youtube and tha…
  • 18.08.2009 — Permissions Using Bitwise (2)
    This will be a quick tutorial on how to use bitwise operators in PHP to create permissions control. …
  • 11.08.2009 — Sql Queries Cache (0)
    This will be intermediate tutorial about caching SQL query results. We will use interface to make su…
  • 16.07.2009 — Advanced PHP User Login (8)
    If you ever had a bank account you are familiar with TAN-s (Transaction Authentication Number). What…
  • 19.04.2009 — Multi-query function (5)
    I needed a function that will take a string or a file and then split it into small SQL queries. I fo…

logo

Leave a Reply


 *


 *


logo
logo
Powered by Wordpress | Designed by Elegant Themes | CopyRight ©2010 php4every1.com