Saturday, May 21, 2016

PHP Tips and Tricks to Improve Your Programming Skills

Guys if you love to PHP programming. Listed below are some excellent techniques that PHP developers should learn and use every time they program. They can improve their PHP programming skills to follow these tricks.


Avoid the use of printf function
Unlike print and echo, printf() is a function with associated function execution overhead. More over printf() is designed to support various formatting schemes. To handle formatting printf() needs to scan the specified string for special formatting code that are to be replaced with variables.
<?php
echo 'FinalResult:', $result;  
// is better than
printf("FinalResult.%s", $result );
?>

echo is faster than print
PHP is giving some sting functions to printing output into browser and we are often using print() and echo() function.
Print() function behavior like the other function in common and having return value integer 1. Thus, print() can used as part of expression which more complex. Meanwhile, echo() is able to accept more than one parameters all at once, and does not having return value.
<?php
print() 'string 1';
echo 'string 1';
// using some parameters
echo 'string 1', "string 2", '...';
?>

echo() function string will execution more faster than print(). This differentiate caused by will return status (integer) which expose what process has done or not.

Loops and Counting
Here are some ways to make your loops and counting a bit more efficient.
Use pre-calculations and set the maximum value for your for-loops before and not in the loop. This means you are not calling the count() function on every loop.

$max = count($array);
for ($i = 0; $i < $max; $i++)
//is faster than
for ($i = 0; $i < count($array); $i++)
When checking the length of strings:
Use isset where possible in replace of strlen. (cite)
if (!isset($foo{5})) { echo "Foo is too short"; }
//is faster than
if (strlen($foo) < 5) { echo "Foo is too short"; }


Single Quotes vs Double Quotes
You may or may not think about this point in your PHP use but it is kind of a big deal. Using the right or wrong quotes can not only cause errors that might be hard to find but there can be a slight performance boost and can make your code much easier to read.
    <?php
         echo 'hello world in techbowl';
    ?>
    <?php
         echo "hello world in techbowl";
    ?>
These will produce the exact same end result but do you know which one is technically better? The single quote. The single quote just puts exactly what is inside of it without processing while the double quote actually evaluates and processes. Let’s take an example.
    <?php
   
          $example = 'hello world in techbowl';
   
          echo '$example'; // outcome will be $example
   
          echo "$example"; // outcome will be hello world in techbowl
    ?>
As you can see here the double quotes take the time to process what is inside so technically there will be a little more overhead.
Obviously on a small scale this means nothing but if you have a loop that iterates 1000 or more times you might start to see the benefits of single quotes in a performance sense.

When incrementing:
Use pre-incrementing where possible as it is 10% faster.
++$i;
//is faster than
$i++;
And
Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

Accessing arrays
For Example:  $result['post_id'] is 7 times faster than $result[post_id]

Avoid functions inside loops
Try to use functions outside loops. Otherwise the function may get called each time and obviously it will affect performance.
<?php

    /*  loop with a count() inside the control block will be
        executed on EVERY loop iteration.
    */
    $count = count( $array );  
    for( $i = 0; $i < $count; $i++ )  
    {  
        // do something here
    }  
     
    // is better than          
    for( $i = 0; $i < count( $array ); $i++ )  
    {  
        // do something here
    }
?>
It's even faster if you eliminate the call to count() AND the explicit use of the counter by using a foreach loop in place of the for loop.
<?php
    foreach ($array as $i) {
        // do something  
    }
?>


Use absolute paths in includes and requires
It means less time is spent on resolving the OS paths.
include('/var/www/html/your_app/test.php');
//is faster than
include('test.php');
require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference.

true is faster than TRUE
This is because when looking for constants PHP does a hash lookup for name as is & since names are always stored lower cased, by using them you avoid 2 hash lookups. Furthermore, by using 1 and 0 instead of TRUE and FALSE, can be considerably faster.

Use isset() instead of strlen() function
<?php
$str = "45e23";
if (!isset($str{5})) {
    echo 'String must be at least 5 characters<br />';
}
if (strlen($str) < 5){
    echo 'String must be at least 5 characters;
}
?>
isset() needs little more time than strlen() because isset() is a language construct.
When you treat strings as arrays, each character in the string is an element in the array. By determining whether a particular element exists, you can determine whether the string is at least that many characters long. (Note that the first character is element 0, so $str[5] is the sixth character in $str)

Use ternary operators instead of if, else
Ternary operators can be very helpful and clean up the code, but don’t over complicate them otherwise your code might become inundated with large amounts of complex ridiculousness.
<?php
$name = (!empty($_GET['name'])? $_GET['name'] .'techbowlarticle');
?>

one-liner to convert XML into associative array.
<?php
$arr = json_decode(json_encode(simplexml_load_string($xml, null, LIBXML_NOCDATA)), true);
?>


Maintain debugging environment in your application

During development we echo database queries , dump variables which are creating problems , and then once the problem is solved , we comment them or erase them. But its a good idea to let everything stay and help in the long run

On your development machine you can do this :

[code]
define('ENVIRONMENT' , 'development');

if(! $db->query( $query )
{
    if(ENVIRONMENT == 'development')
    {
        echo "$query failed";
    }
    else
    {
        echo "Database error. Please contact administrator";
    }  
}
[/code]

And on the server you can do this :\
[code]
define('ENVIRONMENT' , 'production');

if(! $db->query( $query )
{
    if(ENVIRONMENT == 'development')
    {
        echo "$query failed";
    }
    else
    {
        echo "Database error. Please contact administrator";
    }  

}
[/code]

Omit the closing php tag if it is the last thing in a script
Let's have a look on below code
<?php

echo "Hello";

//Now dont close this tag

This will save you lots of problem. Lets take an example :

A class file super_class.php
<?php
class super_class
{
    function super_function()
    {
        //super code
    }
}
?>
//super extra character after the closing tag
Now index.php

require_once('super_class.php');

//echo an image or pdf , or set the cookies or session data
And you will get Headers already send error. Why ? because the "super extra character" has been echoed , and all headers went along with that. Now you start debugging. You may have to waste many hours to find the super extra space.

Hence make it a habit to omit the closing tag :

<?php
class super_class
{
    function super_function()
    {
        //super code
    }
}

//No closing tag
That's better.


So there were few tricks and tips to improve the PHP programming skills, hope you will follow these and love these.


7 comments: