Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

multi-dim array unset using $globals help

Status
Not open for further replies.

drska

Programmer
May 21, 2004
14
HR
Hi!
Here is my problem:
<?php
$arr["a"][0]["x1"]="222";
$arr["a"][0]["x2"]="22A";
function clear(){
global $arr;
unset ($GLOBALS[???])
}

so, I wan't to unset elements of multidimensional array in
a function, and since in documentation says that unless
$GLOBALS is used, array won't be unset in the "main part of the script".
So, how to solve this?
I need multidim. arrays, and they have to be in a funciton, since it is a recursion.
 
You are mixing two concepts here.
There is the superglobal array that contains all global values, such as $_POST etc. However, that has nothing to do with what you are trying to achieve. $GLOBALS is not inplay at all.

Your question is about scope and passing the array to a function. That's something completely different.

1. When you use global $foo you access the variable $arr from inside a function - that's one way of getting access to the array. All you would need to do is
Code:
<?php
$arr["a"][0]["x1"]="222";
$arr["a"][0]["x2"]="22A";
clear();
exit;

function clear(){
 global $arr;
 unset ([COLOR=red]$arr[/color]);
}
?>

2. There is an alternate solution which will allow you to use the function not just on one named variable. The concept is that you pass the array by reference. What that means is that the var passed into the function is pointing to the same information/content. You can then manipulate the var from inside the function and affect the original var as well.
Code:
<?php
$arr["a"][0]["x1"]="222";
$arr["a"][0]["x2"]="22A";
clear($arr);

function clear(&$theArray){
 unset ($theArray);
}
?>
The ampersand in the function declaration is what makes the variable be passed by reference. Now it doesn't matter which array you pass - any array can be cleared using the same function.
 
Ok, thnx, second solution seem to work...!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top