PHP5 and tiny foreach() improvement

While this issue is certainly not specific to CakePHP, I felt it was worthwhile to point out since we are often dealing with data arrays and foreach() loops to modify that data.

Consider the following example:

function afterFind($results, $primary=false) {
      if($primary == true) {
        foreach($results as $key => $value) {
            $results[$key][$this->alias]['my_field'] = $this->modifyField($value[$this->alias]['my_field']);
        }
      }

      return $results;
}

While this works just fine for most cases, the main issue is that $value in the above example is actually a copy of the array’s content.

In PHP5 we have the option to reference the array elements of $results, by using: “$results as &$value”.

So the modified code for PHP5 would look like:

function afterFind($results, $primary=false) {
      if($primary == true) {
        foreach($results as &$value) {
            $value[$this->alias]['my_field'] = $this->modifyField($value[$this->alias]['my_field']);
        }
      }
      unset($value);

        return $results;
}

The obvious improvement is that we are not creating any extra copies of our data. Sure, it may not cause any serious issues, but if making additional copies of the data can be easily avoided it probably should be. Secondly, it makes the code cleaner and more concise, which is always a good thing.

P.S. It is always a good idea to unset() the reference in case any further processing might accidentally change the value of our $results array.

Related Posts

%d bloggers like this: