PHP Tricks

Here are some useful tricks on PHP that will reduce the length of the code:

  1. The or Operator
  2. String as Array
  3. Suppress errors

The or Operator

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.

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
$string = "Hello world!";
$string[0]; //the 1st(or 0th in the index) character is "o"
?>

However, you can't echo part of the string with that way, you need to use type casting or a function to convert it to an array. I tried to retrieve a part of a string by using that way, and it worked, but I'm not sure with shuffle() strings.

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. (example: @file_get_contents("http://does.not.exist.com/nothing" will not generate error message if the command was failed.) However, fatal errors/parse errors will still be shown.