0

Say we have this array of strings:

$arrString = ["1", "2", "3"];

One traditional way of converting the values to integers are like so:

foreach ($arrString as $key => $value)
    $arrString[$key] = (int) $arrString[$key];

echo var_dump($arrString);

This outputs:

array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }

Much expected. However, I believe using a reference is a much quicker way of getting the same work done:

foreach ($arrString as &$strValue)
    $strValue = (int) $strValue;

 echo var_dump($arrString);

Well guess what it outputs?

array(3) { [0]=> int(1) [1]=> int(2) [2]=> &int(3) }

Which is to say it assigned the last value as a reference to an int. This always happens to the last element when using a reference in the loop (even when there's just one element), and it also happens irrespectively if I use the (int) cast or PHP's settype- and intval functions.

It beats me; Why is this happening? And should I really care?

Martin Andersson
  • 18,072
  • 9
  • 87
  • 115

1 Answers1

3

You should care, and it's been explained many times before here on SO (and there's an explicit warning in the PHP documentation)

Do

unset($strValue);

after the loop

See here for an explanation

EDIT

Reference

with quote:

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

Community
  • 1
  • 1
Mark Baker
  • 209,507
  • 32
  • 346
  • 385