1

So with this code:

$x = 'hello  world';
$y = 'bye world';
$arr = array ($x, $y);

$arr[0] = 'new string';
var_dump($x);

$arr[0] = 'new string'; it's not changing the value of $x. How can I change $x value referencing the array position?

1
  • print_r($arr) you are going to replace array[0] index value Commented Jul 30, 2020 at 11:02

2 Answers 2

1

The value of $x will be copied to the array! There is no reference from $arr[0] to $x!

Sign up to request clarification or add additional context in comments.

Comments

0

You could create a reference to $x, instead of copying the variable. When passing it into the array as you are, you are merely copying the value of $x, and inserting that copy into the array. If you instead pass $x as a reference, using &$x, any updates made will be made to $x instead. Since the value is a reference, it will be updated "both places".

$x = 'hello  world';
$y = 'bye world';
$arr = array (&$x, $y);

$arr[0] = 'new string';
var_dump($x);

Output:

string(10) "new string"

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.