0

I have two arrays, both with the same indexes. What I want to do is loop through one of the arrays (portConfigArray), and change the value of an existing item by using data from a second array. (portStatusArray) Here's the logic:

$i=0;
foreach ($portConfigArray as $configentry)
{           
    $configentry['LinkState'] = $portStatusArray[$i]['LinkState'];
    $i = $i + 1;
    echo $configentry['LinkState'];             
}
$portdetailsArray = $portConfigArray;
var_dump($portdetailsArray);

the echo statement shows the correct values being assigned for each item in the portConfigArray. (its just a string value like "Up" or "Down") But in the var_dump I can see that the value hasn't been updated correctly. It shows

["LinkState"]=> string(0) "" 

as the output for each record.

Can you tell me what I'm doing wrong?

3 Answers 3

1

You need to make $configentry a reference, otherwise it's just a copy

foreach ($portConfigArray as &$configentry)
Sign up to request clarification or add additional context in comments.

2 Comments

This can blow up on you, because $configentry will STAY a reference until you unset() it, or the script ends. If you reuse $configentry later in the script, you'll be changing the LAST element you foreach'd on, which can cause serious confusion.
Agreed. You should always be diligent when using references.
1
foreach ($portConfigArray as $configentry)

Should be

foreach ($portConfigArray as &$configentry)

Essentially this means the loop deals with the actual value rather than a copy of it.

Comments

0

While you can make $configentry a reference, as stated in other answers, it CAN cause major issues if you reuse such "referenced" variables later on in the script for other purposes. A safer method is to use the key=>val version of foreach, and directly modify the array:

foreach($portConfigArray as $key => $configentry) {
    $portConfigArray[$key] = 'newvalue';
}

The reference version can cause issues, e.g.

php > $a = array('a', 'b', 'c');
php > foreach($a as &$val) { $val++; };
php > print_r($a);
Array
(
    [0] => b
    [1] => c
    [2] => d
)
php > $b = array('p', 'q', 'r');
php > foreach($b as $val) { $val++; };  <--note, $val, not &$val
php > print_r($b);
Array
(
    [0] => p   <---hey, these 3 didn't change!
    [1] => q
    [2] => r
)
php > print_r($a);
Array
(
    [0] => b
    [1] => c
    [2] => s  <---uh-oh!
)
php >

Comments

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.