Tuesday, January 27

Pass Reference to Function in PHP

Pass reference to the function if it does not affect your logic. A function manipulating the reference is faster than those manipulating the value been passed as here one more copy of the value is getting created. Especially it adds overhead when the value passed by you is a big array.

For example, let us create a function in two different way to increment by 1, each element of an array having values 0 to 99.


<?php
  // passing by reference
  function  computeValue( &$param ){
  // Something goes here
  foreach( $param as $k => $value){
   $param[$k] = $value + 1;
  }
  }
  $x = array();
  for( $i =0; $i<99; $i++){
    $x[$i] = $i;
  }
  computeValue( $x);
  
  // array with 100 elements each incremented by 1
  print_r( $x );

?> 

The function above works faster than the function below although both will produce the same result ( increment each element of the array by 1. )

<?php
  // passing by value
    function  computeValue( $param ){
      // Something goes here
      foreach( $param as $k => $value){
      $param[$k] = $value + 1;
      }
      
      return $param;
    }
    $x = array();
    for( $i =0; $i<99; $i++){
      $x[$i] = $i;
    }
// array with 100 elements each incremented by 1
    print_r(computeValue( $x));
    
  ?>

No comments:

Post a Comment