Categories
Coding PHP

PHP assign variable by value or reference.

I did a similar exercise on CodeCademy and it had me stuck at first, so I had to copy the code into my own editor and study it. It’s not that it was hard, but just confusing at first. After that I decided to create my own version with some extra echos of what is going on.

Basically we have two variables, both are set to associative arrays (key => value) with the same key names but with different values. Then we have created a first function that is designed to accept an array as an argument using our pre made variable tempArray($temp_arr) this just returns the array with some changes added inside the function to two of the values.

The second function changeArray(&$change_arr) does the same thing with the second pre made variable, but changes the values in memory. A bit tricky at first to understand by just reading so check out the code.

The point is if this page of code were to continue and we made use of the two original array variables ($temp_arr or $change_arr) again after being triggered using the functions the variables would either be the same or have new values. Just depends on the function used.

Edit, I always misspell the word “function” with fucntion. Must be my Macbook 🙂

This code could be changed to accept dynamic arguments, but for this the arguments were hardcoded inside the functions.

Note I wrapped the <pre> tags around the php code tags to make the print_r easier to read.

<pre>
<?php

//The two variables, both are set to arrays with different initial values.

$temp_arr = ["Temperature" => "Cold", "Weekday" => "Monday", "State" => "Kentucky"];

$change_arr = ["Temperature" => "Hot", "Weekday" => "Tuesday", "State" => "Texas"];


//tempArray(array) will return a temporary result using the new values inside the function.
function tempArray($arr) {
    $arr["Temperature"] = "Cool";
    $arr["State"] = "Washington";
    return $arr;
}

//this variable is triggering the function tempArray() using $temp_arr as its argument.

$temp_var = tempArray($temp_arr);

echo "Temp array with some temp changes, but the \$temp_arr value is not actually changed\n";
print_r($temp_var);
echo "\n";

//changeArray(array) only code change is &$ returns a changed result.
function changeArray(&$arr) {
    $arr["Temperature"] = "Freezing";
    $arr["State"] = "Alaska";
    return $arr;
}
//Triggering the function changeArray() with $change_arr variable as its argument.
$change_var = changeArray($change_arr);

echo "Changes the values of \$change_arr\n";
print_r($change_var);

//Some extra printing
echo "\n";
echo "Lets now verify the original \$temp_arr and \$change_arr values after both functions have been used.!\n";
echo "\n";
echo "\$temp_var is still.\n";
print_r($temp_arr);
echo "\n";
echo "\$change_var is now!\n";
print_r($change_arr)

?>
</pre>

Leave a Reply

Your email address will not be published. Required fields are marked *

21 − = 16