Wednesday 8 October 2014

The use of "===" instead "==" to test the result of a function

When managing one error, which is returning from a function, I have been faced with the importance of using "= = =" instead of " =  = " ;

Imagine the following case: a function with database query within a foreach with a control from the query return (here, we have just a 'select' but it could have been an 'insert',  an 'update', a 'delete' etc..)


[..]
foreach ($parcels as $aparcel)
{
$events = $this->getEvents($aparcel[id]);
if ($events === false)
        {
$_aMsgs['errors'][$i] = "Error in the resulting data getParcelsEvents";
$i = $i + 1;
continue;
       }
       else { //using $events for doing stuff even if empty
     
       }
}
[..]

protected function getEvents($parcelsid)
{

   $sQuery = "select [fields]
   from [table] (nolock)
   where no_colis = '$parcelsid';";

$oStatement = mysql->prepare($sQuery);

$bResult = $oStatement->execute();
if (!$bResult)
{
//echo $sQuery.PHP_EOL;
return false;
}
return $oStatement->fetchAll(\PDO::FETCH_ASSOC);
}


At start, I was using "if ($events = = false)" to control the results from the getEvents function, but, doing so,  one empty result from the database query was considered as an error - that was not the behavior that I was expected ; the solution was to use "=  =  =" to be sure to test only the "false" returning case and not that empty case !!!

From now on, I am using mostly the triple "=" when dealing return of a function!