Some PHP Hacks Every Programmer Should Know

php-hacks-tips-tricks-every-programmer-should-know-codexworld

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 {
    
//something

} catch (Exception $e) {
    echo 
'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''john@example.com'];
list(
$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 'john@example.com';
compact('name''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');
$input->int('anotherKey'55);

Conclusion

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.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

4 Comments

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

Leave a reply

keyboard_double_arrow_up