1

Here's sample code:

<?php

$arr1 = [ 'foo' => 'bar', 'test' => '2' ];
$arr2 = [ 'foo' => 'bar', 'test' => '2' ];

$arr3 = [ $arr1, $arr2 ];

$randomArr = $arr3[mt_rand(0, count($arr3) -1)];

$randomArr['test'] = 3;

echo "$arr1: " . print_r($arr1, true);
echo "$arr2: " . print_r($arr2, true);

What I'm trying to do here is change the value of $arr1['test'] or $arr2['test'], at random, to 3. It seems $randomArr gets copied by value and not by reference. Is there a way to do a copy by reference so that I can change $arr1 or $arr2 inline?

1

2 Answers 2

6

You can create an array of references to your other arrays.

$arr3 = [ &$arr1, &$arr2 ];

Then update one of the arrays directly without creating $randomArr.

$arr3[mt_rand(0, count($arr3) -1)]['test'] = 3;
Sign up to request clarification or add additional context in comments.

2 Comments

What if multiple keys need to have their values updated for the same array?
In that case you could create $randomArr as before, but assign it by reference as well. Pretty much like the other answer that @gview added just as I replied to your comment :)
4

Or you can using your code do this as well:

<?php

$arr1 = [ 'foo' => 'bar', 'test' => '2' ];
$arr2 = [ 'foo' => 'bar', 'test' => '2' ];

$arr3 = [ &$arr1, &$arr2 ];

$randomArr = &$arr3[mt_rand(0, count($arr3) -1)];

print_r($randomArr);
$randomArr['test'] = 3;

echo "$arr1: " . print_r($arr1, true);
echo "$arr2: " . print_r($arr2, true);

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.