Important PHP Tips & Tricks

October 20, 2018 by admin

While working on medium and big level project many developers faced problem related to speed up website. PHP is easiest language to learn and with new releases its getting better and better.

To become better PHP programmer, we need constant improvement in terms of solutions we apply to regular code and optimize them more effeciently to reduce memory usage and improve site performance.

Advantages of PHP is, it is most loved and widely used programming language for web development and the best part is, there are so many tutorials available for constantly learning and improving php programming skills.

This blog mainly focuses on reducing time and use tips and trick for the current project to avoid slow website issue and enjoy your professional work hassle free.

1. Avoid count function call in iteration

Most of the time, we try to avoid assigning a function response to variable because we want to save extra memory assigned to variable.

Here, in this case we are trying to save one single variable's memory.But with good practice we can use this same variable to save memory.

/* Bad practice */ 
for( $i=0; $i < count($someArray); $i++ ) {
       // other operations 

/* Good Practice */
$arrLength = count($someArray);  
for( $i=0; $i < $arrLength; $i++ ) { 
      // other operations 

So, in above code, we can say that assigning function value to variable will save count value to only one memory location because it avoids the count() function call on every iteration.

Hence, we have avoided unnecessary function calling at each iteration.

COUNT (php 4, php 5, php 7): Count all elements in an array, or something in an object.

Syntax:   int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Reference Link:   php count function

2. Get digits from any string

Small but important tip to get only digits (int/float) from the given string.

Sometimes we get string which itself includes important id or value.

Following code snippet will get string as an input value and return all the integer/float values hidden in it.

$str = "He got 89.9945percentage"; 
var_dump( filter_var( $str, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ) ); // 89.9945

where - filter_var -> is function available in PHP to filter a variable with a specified filter.
FILTER_SANITIZE_NUMBER_FLOAT -> Remove all characters except digits, +- and optionally .,eE
FILTER_FLAG_ALLOW_FRACTION -> will receive fraction value as well if any

3. comparison operator (ternary operator)

Comparison operators, as their name implies, allow you to compare two values.

// Example usage for: Ternary Operator 
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

If $_POST['action'] is not empty then it will evaluates to true and $action will contain 'default' value otherwise value in $_POST['action']

There is another conditional operator is the "?:" (or ternary) operator.

$value = 'This is Interesting'; 
$result = $value ?: 'Other Value'; // $result is set to 'This is Interesting' because $value is evaluated to TRUE 
$value = ''; 
echo $value ?: 'Other Value'; // 'Other Value' will be printed because $value is evaluated to FALSE

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Reference Link:  comparision operator

4. Find text within string

Many time, we faced a situation where we need to find existance of particular word/characters/string withing long string- So, generally we try following code to check whether a particular word/characters/string is present exists or not.

$needle = 'findme';
$haystack = 'findmeyahoo';
if (strpos($needle,$haystack)) {
  echo $needle ." contains ". $haystack;
} else {
  echo $needle . " does not contain " .$haystack;


"yahoogoogle" does not contain "yahoo"

The problem here is that strpos() returns the starting position index of $needle in $haystack (if found), otherwise it returns false. So In this example, strpos() returns 0 (which results to false when referenced in the if statement). So this is the reason it will always execute else statement in above scenario.

So, to solve this problem, we need to explicitly compare the value returned by strpos() to false as follows:

$needle = 'findme';
$haystack = 'google';

if (strpos($needle, $haystack) !== false) {
  echo $needle . " contains " . $haystack;
} else {
  echo $needle . " does not contain " .$haystack;
Note that-

Here, in this case, we have used the !== operator and not just the != operator.This is because != will just compare value with 0 with false and as this statement will return false, we'll be once again on the first example. So to solve this problem we've used !== because it will strictly check the type of either side of the statement, now this time it will return true .