0

I have an array, lets call $x, so

    $x = array(
               'a'=> 1,
               'b'=> 2,
               'c'=> 3
              );

I wants to replace the value of suppose for c, so I can do it by

$x[c] = 4;

Its works, but if I want to do it using a function, I can write a function

function changevalue ($a, $k, $v) {
    $a[$k] = $v;
    return $a;
}

and then use this function to change the value

changevalue($x, 'c', 4);

it doesn't work, but if I set it equals to $x

$x = changevalue($x, 'c', 4);

it works. my question is why I need to set the function equals to the array. I'm new to PHP, it will be very helping if someone explains. Thanx in advance. :)

Enam
  • 95
  • 1
  • 1
  • 9
  • 1
    Have a look at [this post](http://stackoverflow.com/questions/2030906/are-arrays-in-php-passed-by-value-or-by-reference). – diiN__________ Oct 04 '16 at 07:12
  • 1
    in this you just change the array value but you agian access the array but in second you assign the value to the variable for this whether you have to echo the value in the function or return the value –  Oct 04 '16 at 07:13
  • Thanks, @diiN_, it helped. :) – Enam Oct 04 '16 at 07:44

1 Answers1

2

You are passing $x by value. You can try passing it by reference instead, by doing this (adding the & symbol):

function changevalue (&$a, $k, $v) {
                      ^
    $a[$k] = $v;
    return $a; // This is not necessary if you are passing by reference
}
Rax Weber
  • 3,730
  • 19
  • 30