PHP Tricks
Here are some useful tricks on PHP that will reduce the length of the code:
- The or Operator
- String as Array
- 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
mysql_connect("localhost", "username", "password") or die("ERROR: Unable to connect");
?>
The code generally describes:
- Attempt to connect to database.
- If step 1 failed, the code after
or will be executed.
- The code after
or is die(), which will end the script with a message.
- Otherwise, don't execute the code after
or .
It's also a same version of:
<?php
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];
?>
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.
|