PHP tricks Part 1



I’m going to post a few php tricks here and there for my audience (if there’s any) to have fun with.

Trick 1 : Triple Equal “===”
Usage : if($a===$b)
Reason : === is used to make like easier for the (advanced) php programmer. It forces a comparison within the same type thus eliminating some programming checking codes.

$input = 1;

if($input == true)
{
    echo "input is not boolean true but it passed anyway!";
}

if($input === true)
{
   echo "input needs to be boolean true to pass this if statement";
}

//What's so useful?

if($_GET[something]===0)
{
    echo "My form recieved exactly a 0, not a blank, not a false... but a 0!";
}elseif(!$_GET[something])
{
   echo "could be a null,blank or false";
}

Trick 2 : echo comma
Usage : echo $a,$b,$c,$d;
Reason : Less memory usage, less cpu cycles, faster output to screen and… bragging rights.

$a = "hel";
$b = "lo";
$c = " wor";
$d = "ld";

echo $a.$b.$c.$d;
//What actually happens is that the string is buffered (added) together
// before sending to output

// $a .=$b     adds "hel"+"lo"
// $a .=$c     adds "hello"+" wor"
// $a .=$d     adds "hello wor"+"ld"
// echo $a     echos out "hello world"

echo $a,$b,$c,$d;
//What actually happens is that the string is not added but sent directly to output
// echo $a   => echos out "hel"
// echo $b   => echos out "lo"
// echo $c   => echos out " wor"
// echo $d   => echos out "ld"

That’s all for this week… till i have time to blog again… cheers

1 Comments Say Something
  • Another use of “!==” would be to end arrays which have blank “” or 0.

    ie :

    $arraytest = (0,””,”testing”,”\0″);

    //add to array to end it
    $arraytest[] = false;

    for($i=0;$arraytest[$i]!==false;$i++)
    {
    echo “ARRAY $i : “.$arraytest[$i];
    }

Add A Comment