Angel Politis
Angel Politis

Reputation: 11313

Issue with passing values by reference into an array

I have an array named $initValues, which contains strings or numeric values and using a foreach loop I want to transfer the values to the $values array and the type of each value to $types.

Code:

$initValues = ["1-2", "2-1"];
$values = [];
$types = [];

foreach ($initValues as $value) {
    $values[] = &$value; # by reference.
    $types[] = gettype($value);
}

As you can see in the above code, I'm inserting the value by reference in $values, which is required by a function used later on, so that can't be changed. When I execute the above code and show the result using var_dump($values), I get the following:

array(2) { [0]=> &string(3) "2-1" [1]=> &string(3) "2-1" }

The problem with the above result is that essentially both elements of my $values array are the last element of $initValues and not both as in the desired result, which is:

array(2) { [0]=> &string(3) "1-2" [1]=> &string(3) "2-1" }

If I enter each value by value into the array the result is correct, but I'm facing a problem later on, so that's not an option. How can I modify my code, in order to produce the desired result?

Upvotes: 0

Views: 47

Answers (1)

crystalAhmet
crystalAhmet

Reputation: 366

Use an index in your foreach loop. This should work:

$initValues = ["1-2", "2-1"];
$values = [];
$types = [];

foreach ($initValues as $ix=>$value) {
    $values[] = &$initValues[$ix]; 
    $types[] = gettype($value);
}
var_dump($values);

Upvotes: 2

Related Questions