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()
Usingarray_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 usingunserialize()
, instead that use json_encode()
.5. PHP list() function
Uselist()
function to assign variables as an array.Instead of:
$person = ['John Thomas', 'john@example.com'];
list($name, $email) = $person;
$name = $person[0];
$email = $person[1];
6. PHP compact() function
Usecompact()
function to quickly create an array using key as the variable name.Instead of:
$name = 'John Thomas';
$email = 'john@example.com';
compact('name', 'email');
['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);
Comments