Amazon Prime Day August 2020

Best practices for optimizing php code


 If you are follow these points, you can reduce execution time of php script as well as get best performance.

1). Ternary Operator
Use Ternary Operator instead single if else condition. In ternary condition we can use “? ” and “:” symbols.
Syntax : ($x > 5 ) ? ‘true’ : ‘false’;
Above condition, first $x > 5 is evaluated if it is correct returns true or not returns false.

2). ($foo{5}) is faster than strlen($foo) < 5

3) array_column:  Return the values from a single column in the input array.
E.g:
       

$states = array(
    array(
        'id' => 11,
        'country_id' => '201',
        'state_name' => 'California',
    ),
    array(
        'id' => 12,
        'country_id' => '201',
        'state_name' => 'Florida',
    ),
    array(
        'id' => 13,
        'country_id' => '201',
        'state_name' => 'New Jersey',
    ),
   
);

$state_names = array_column($records, 'state_name');
print_r($state_names); 



4). ctype functions:
By using ctype functions like ctype_alpha(), ctype_digit(), ctype_alnum() validates the given string and avoid the illegal inputs at server side.

5). list():  we can create and assign the values of array while explode the array.
E.g:  $date = ‘12-08-2016’;
     list($date,$month,$year) = explode(“-”,$date);

6). Don’t use count() in for loop
Wrong code:
    $arr = array(‘apple’,‘mango’,‘grape’,‘banana’,‘orange’);  
for($i = 1; $i <= count($arr); $i++  ){
Echo $arr[$i];
}
In the above code, the size of $arr is evaluated many times.
Correct code:
    $arr = array(‘apple’,‘mango’,‘grape’,‘banana’,‘orange’);  
$arr_length = count($arr);
for($i = 1; $i <= $arr_length; $i++  ){
Echo $arr[$i];
}


7). Isset() :
   By using isset(), we can eliminate the undefined index notices for variables. This notice mainly occured in dynamic array iterations.

8). Variable declaration:
While using any new variable or array,  declare it’s data type starting of script or function.
// String
$var = ‘’;
// Integer
$i = 0;
// Array
$months = array();


 9). Pass Reference to Function
Pass reference of parameter to function is faster thane passing parameter to function. It does not  affect any execution flow.

<?php
  // passing reference parameter
  $param = array();
  function multiply( &$param ){
    foreach( $param as $key => $val){
     $param[$k] = $val * $val;
   }
Return $param;
  }
  $numbers = array();
  for( $i =0; $i<50; $i++){
    $numbers[$i] = $i;
  }
  $res = multiply( $x);
  print_r( $res );

?>    

10). Use switch case method instead of nested if else condition while developing php script.



Post a Comment

0 Comments