03-Apr-2023
.
Admin
Hi guys,
Today i will explained to php tips and tricks to write a more structured PHP script in less time. THis articalis also working with php. You should always use the following PHP hacks while coding in PHP.
So let's start to the artical.
Ternary Operator
The Ternary Operator consistent with three expressions to separated by a question mark (?) and a colon (:) sign. Its working to if/else logic to shorter,quickly,and faster.
Ternary Operator use to your script to save line and script length as long as they are simple.
$name = !empty($_GET['name'])? $_GET['name'] : 'nicesnippets';
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. The PHP Exception Handler is a samrt to handle exception condition.
try {
//something
} catch (Exception $e) {
echo 'Message: ' .$e->getMessage();
}
array_key_exists() vs in_array()
Using array_key_exists() and instead of in_array() is a good choice, because array_key_exists() is faster than in_array() function.
unserialize() vs json_encode()
Try to avoid using unserialize(), instead that use json_encode().
PHP list() function
Php list() function to assign to the variables to the array.
$user = ['mark Thomas', 'mark@gmail.com'];
list($name, $email) = $user;
Instead of:
$name = $user[0];
$email = $user[1];
PHP compact() function
compact() function to create quickly an array using key as the variable name.
$name = 'mark Thomas';
$email = 'mark@gmail.com';
compact('name', 'email');
Instead of:
['name' => $name, 'email' => $email]
Default Variable Value
variable always assign to the default value
$var = "default";
if (condition) {
$var = "something";
}
Now you can check your own.
I hope it can help you...
#PHP 8
#PHP