It is indeed a scope issue. Normally, when you pass the $lakearray argument to your remove_lake() function, a copy of this object is created in memory, and the function will only be able to manipulate that copy, not the original (here, the $locations object in your main program).
You have three ways to achieve the desired goal:
-> Make the $locations variable accessible from inside your function using the GLOBAL keyword. This is usually considered bad practice and you should avoid it, but here's an example for information:
Code:
firas@nobue ~ % cat test.php
<?php
$locations = array("foo", "bar");
function remove_lake($lakename)
{
GLOBAL $locations;
// the following assignment is deliberate
if(($key = array_search($lakename, $locations)) !== false) {
unset($locations[$key]);
}
else print "<br />## That lake was not found. ## <br /><br />";
}
remove_lake("foo");
var_dump($locations);
?>
firas@nobue ~ % php test.php
array(1) {
[1]=>
string(3) "bar"
}
-> Use the return value of the function to pass the modified array to the rest of your program:
Code:
firas@nobue ~ % cat test.php
<?php
$locations = array("foo", "bar");
function remove_lake($lakename, $lakearray)
{
// the following assignment is deliberate
if(($key = array_search($lakename, $lakearray)) !== false) {
unset($lakearray[$key]);
return $lakearray;
}
else {
print "<br />## That lake was not found. ## <br /><br />";
return NULL;
}
}
$locations = remove_lake("foo", $locations);
var_dump($locations);
?>
firas@nobue ~ % php test.php
array(1) {
[1]=>
string(3) "bar"
}
-> Use object-oriented programming, but that will take a bit more work. You can stick with #2 for now.
Also, notice that I changed the test in your function. Try to find out by yourself why yours was wrong.
Bookmarks