Efficiency of PHP Query Execution PHP

4

Is there any performance difference in the codes below?

$result = $pdo->query($sql);
foreach($result as $reg){ ... }

and ...

foreach($pdo->query($sql) as $reg){ ... }

I did some testing, but the behavior of the runs does not seem to be standard, so I can not figure out if there is a difference. Sometimes it looks like code 1 is faster and sometimes it seems like there is no difference at all. I would like to know how the PHP interpreter works in both cases, and if there is indeed any difference in performance.

Thank you.

    
asked by anonymous 29.01.2016 / 18:40

1 answer

2

The way you do there is no difference in performance. The results will be the same.

The question of assigning or not the variable to iterate it with foreach will make a difference in the following cases:

  • I want to change the array value in foreach .
  • Foreach with reference

Example:

$range = range(1, 10);

foreach ($range as $key => $value)
{
      $range[$key] = $value * 2;
}

Or even with reference:

foreach ($range as $key => &$value)
{
    $value = $value * 5;
}

When we do in the second case, the $range will be changed by reference.

 print_r($range);

The output will be:

   [
     5,
     10,
     15,
     20,
     25,
     30,
     35,
     40,
     45,
     50,
   ]

Beware of References in Foreach

Just to complement, when you use reference in foreach , be very careful, because being a reference, the variable that references the elements of array will always refer to the last element of array . That is:

foreach ($range as $key => &$value)
{
    $value = $value * 5;
}

$value = 'Oi, eu sou o Goku';

The output will be:

[
     5,
     10,
     15,
     20,
     25,
     30,
     35,
     40,
     45,
     "Oi, eu sou o Goku",
   ]

To solve this, you should use unset in $value , to undo the reference and it does not happen, because you might accidentally create a variable just by that name.

Another problem of the reference with foreach is as follows: The last element becomes the value of the penultimate if you make another foreach (if the second foreach is without reference):

 $range = range(1, 5);

This generates:

[1, 2, 3, 4, 5]

Then after that:

 foreach ($range as &$value) {}

 foreach($range as $value) {};

 print_r($range);

The array $range looks like this:

[1, 2, 3, 4, 4]

I hope you enjoyed the "additional reference tips".

    
29.01.2016 / 19:57