Site Admin
Site Admin Founder of MeaningArticles
829 Views

PHP Tips & Tricks Some PHP Hacks Every Programmer Should Know

Hello Dev.

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 web-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'] : 'meaningarticles';


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', '[email protected]'];
list($name, $email) = $user;
<strong>Instead of:</strong>
$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 = '[email protected]';
compact('name', 'email');
<strong>Instead of:</strong>
['name' => $name, 'email' => $email]


Default Variable Value

variable always assign to the default value

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

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.