Some PHP Hacks Every Programmer Should Know


A lot of things are there which you should follow when working with PHP. In this article, we’ll discuss some important PHP hacks among them which every programmer should know about. These PHP tips will help you to write a more structured PHP script in less time. You should always use the following PHP hacks while coding in PHP.

1. Ternary Operator

Ternary operator consistent with three expressions separated by a question mark (?) and a colon (:). It makes if/else logic shorter, quicker, and easier.
Use ternary operator in you script to save line and script length as long as they are simple.

$name = !empty($_GET['name'])? $_GET['name'] : 'CodexWorld';

2. PHP Exception Handler

When an error occurred PHP script displays a fatal error. To avoid the error you should need to write the proper code to handle the exception in PHP script. PHP exception handler is a smart way to handle the exceptional condition.

//trigger exception in try block and catch exception
try {

} catch (Exception $e) {
'Message: ' .$e->getMessage();

3. array_key_exists() vs in_array()

Using array_key_exists() instead of in_array() is a good choice, because array_key_exists() is faster than in_array().

4. unserialize() vs json_encode()

Try to avoid using unserialize(), instead that use json_encode().

5. PHP list() function

Use list() function to assign variables as an array.

$person = ['John Thomas'''];
$name$email) = $person;

Instead of:

$name $person[0];
$email $person[1];

6. PHP compact() function

Use compact() function to quickly create an array using key as the variable name.

$name 'John Thomas';
$email '';

Instead of:

['name' => $name'email' => $email]

7. Default Variable Value

Always assign a default value of a variable

$var "default";
if (
condition) {
$var "something";

8. Use Helper

Use a helper to provide an easy access to user submitted data that may not be in the correct format.

$input->string('key''Default Value');


We hope that the above-discussed PHP tips will help you to make your script more strong. Try to use these PHP hacks while programming in PHP. Apart from that if you know any other hacks, you can share your knowledge by providing the comment below.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You


  1. Mwangi Thiga Said...
  2. Yogesh Singh Said...
  3. Mustafa Zahid Efe Said...

Leave a reply