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.
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';
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();
}
Using array_key_exists()
instead of in_array()
is a good choice, because array_key_exists()
is faster than in_array()
.
Try to avoid using unserialize()
, instead that use json_encode()
.
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];
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]
Always assign a default value of a variable
$var = "default";
if (condition) {
$var = "something";
}
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);
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
very nice post
5&6 are very important
Some of the functions I wouldn’t know. Thanks
They’re really good tips, thanks man. 😉