I'm trying to delete an array element in a function. The manual for unset says to use $GLOBALS but that isn't working for some reason. The following is basically what I am doing. But when I run it, the original array has not been changed. Would someone please point out my mistake?
function DeleteElement($id, $myArray)
for ($i=0; $i < count($myArray); ++$i)
if ($id == $myArray[$i]['id'])
Well...that's not good. I don't know who told you this, but it's completely wrong. The reason is not found in the code, hower, but in the PHP engine itself. It instructs functions that take as arguments arrays, strings, integers,etc. (not objects since PHP5), to make a copy of the original variable and use that when it does stuff with it in the function body. That's why GLOBALS didn't work. You didn't even need them. All you needed to do was declare the function parameter as a reference, not as a variable:
I don't see why you would need this function to delete an element of the array, since you can do it right in place,where you need it. It's unefficient what you do. Here's a better replacement code for that function:
Thanks for the explanation. I didn't use call by reference because when I've tried it before with other code, I always got a message that call by reference has been deprecated, with some php versions. So I don't use it now to avoid that problem. Is that not correct?
With regards to the original post, your use of $GLOBALS was incorrect. The correction would be unset($GLOBALS['myArray'][$i]);
Originally Posted by xenon
Well...that's not good. I don't know who told you this, but it's completely wrong. The reason is not found in the code, hower, but in the PHP engine itself.
The reason is found in the code, not the PHP engine. Passing the array by reference or value is not really the key point; the problem was accessing the correct structure in the $GLOBALS array.
However, it would probably be more beneficial to start over and work with a reference to the array within the function as it would alleviate the need to have the global variable always named $myArray.
The warnings about call-time pass-by-reference being deprecated are only raised when you try to pass an argument as a reference when calling a function (e.g. $blah = myfunc(&$array)) and not when defining a function as accepting arguments by reference (e.g. function myfunc(&$array)).