Home » Php » Pass array by reference and change its value

Pass array by reference and change its value

Posted by: admin October 29, 2018 Leave a comment

Questions:

I have a basic question here about changing array values inside a function, let’s say that I have the following array inside a class:

$my_array = array(1, 2, 3);

And then I have the following method which returns my array;

public function getAnArray()
{
    return $this->my_array;
}

and then I wanna change one value of my_array (2 for example to 7) like this (based on some business logic):

public function changeArray($my_array)
{
    $new_value = 7;

    foreach($my_array as $key => $value){
        if($value == 2){
            $my_array[$key] = $new_value; // Change the value of 2 to 7
        }
    }
}

So that $my_array now becomes (1, 7, 3)

I understand that I have to pass something by reference for this to work, but I don’t know exactly how this should work.

Answers: