Useful PHP Tips

Sep 18, 2013, by admin

Hi all in the post we are going to see some Useful PHP Tips hope this may useful for you the tips are of given below

Tip #1

<?php
$todayTimestamp = time();
/* Don’t Use.*/
$nextDay = $todayTimestamp + 86400;

/* Do instead.*/
$nextDay = strtotime(‘+1 day’, $todayTimestamp);
?>
The first one will not work exactly if you move into or out of daylight savings time.

An extra problem is that the second example is more readable, specially if you add like 2 weeks and 2 days (‘+2 weeks 2 days’)
Use date_default_timezone_set() function before, if you doing calculation to a specific region.

Tip #2

Don’t use regexp to filter/match an email or an URL.There are already built-in filters in PHP for that.

<?php
$email = filter_var(‘scriptarticle@gmail.com’, FILTER_VALIDATE_EMAIL);
?>
See documentation on filter_var()

Tip #3

echo gives you more than one string as parameter.

Using some parameters is going to more faster than blending some variables into a parameter.

<?php
$a = ‘Hello’;
$b = ‘Scriptarticle’;
echo ‘Say ‘ .$a. ‘ to ‘ .$b;

//Below will faster
echo ‘Say ‘, $a ,’ to ‘, $b;
?>

Tip #4

Use isset() instead of strlen() function

<?php
$str = “434e5″;

if (!isset($str{5})) {
echo ‘String must be at least 5 chars<br />’;
}

if (strlen($str) < 5){
echo ‘String must be at least 5 chars’;
}
?>
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)

Tip #5

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 ‘Result:’, $result;
// is better than
printf( “Result.%s”, $result );
?>

Tip #6

Avoid large string concatenation

When do concatenation string, avoid uniting with large size string. It can obstruct code execution that can display faster.

<?php

//Large string concatenation
$title = ‘this is’;
$body  = ‘..a very large blog..’;
echo “Subject.$titlenn$body”;

//Avoid large string concatenation
$title = ‘this is’;
$body  = ‘..a very large blog..’;
echo “Subject.$titlenn”;
echo $body;

?>

To get more updates like the page Bugtreat Technologies and like the page Cs Cart templates for templates updates