Wed. Nov 20th, 2019

Codes

Codes for Coders

PHP Tips to Improve Your Programming Skills

4 min read
Top PHP Tips and Tricks by Rishap Gandhi

Top PHP Tips and Tricks by Rishap Gandhi

Top PHP Tips and Tricks by Rishap Gandhi

In this article we will see the tips and tricks every PHP developer needs to know. These tricks will help you in many ways, lets get right into it..

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
’;
}
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. define('ENVIRONMENT' , 'development');
if(! $db->query( $query ) { if(ENVIRONMENT == 'development') {

echo "$query failed";

}

else

{

echo "Database error. Please contact administrator";

}

}

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.

Source: Techbowl

 

PHP

Leave a Reply

Your email address will not be published. Required fields are marked *