PHP Tricks

Here are some useful tricks on PHP that will reduce the length of the code or optimize the performance.

The or Operator

or (or ||, logical OR) is a logical operator that returns true when ONE side is true. When the left side returned true, the right side will NOT be evaluated, and if the left side returns false, the right side will be evaluated.

For example:
<?php
//Connect to database
mysql_connect('localhost', 'username', 'password')
  or die("ERROR: Unable to connect");
?>

The code generally describes:

  1. Attempt to connect to database.
  2. If step 1 failed, the code after or will be executed.
  3. The code after or is die(), which will end the script with a message.
  4. Otherwise, don't execute the code after or, that means the script will not exit.

It's also a same version of:

<?php
//Connect to database
if (mysql_connect('localhost', 'username', 'password') == false ) {
 die("ERROR: Unable to connect");
}
>> 

String as Array

Did you know what a string can be treated as an array? Just add [ and ] then you can find a specified character in a string.

<?php
$s = 'Hello, world!';
echo $s[0]; //echoes 'H'
?>

Suppress errors

When you evaluated some functions, probably file_get_contents(), an annoying error message will appear if something is wrong. Add @ (at sign) before the statement to suppress errors. (An example is: @file_get_contents('http://does.not.exist.com/nothing' will not generate error message even if it is impossible to get the content.) However, fatal errors/parse errors will still be shown.

The backtick(`) operator

Sometimes, you want to run programs/commands in PHP. You can use the exec() function. However, the backtick is faster. Instead of using $s = exec('ls'), you can use $s = `ls`, the output of `ls` command will be put to $ls. This feature was borrowed from Perl and/or Bash.

Using Single Quotes

Most time, you use strings to access arrays. Many people are still writing $_GET["title"]. It slows down the parser, because the parser is keeping looking for interpolation in double-quoted string. Instead, use single quotes: $_GET['title']. It also applies to echo 'Hello, world!', which does not use variables in the string at all.



Comments

Add Comment