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?

1
  • 1
    fyi- array_walk($arr, 'intval'); Commented May 28, 2012 at 16:44

1 Answer 1

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().

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.