![]() |
How to delete array element in function
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?
PHP Code:
|
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:
PHP Code:
PHP Code:
|
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?
I used the $GLOBALS method since that is what it says to do in the php manual - http://us.php.net/unset The function I posted was just for simplicity. The code involves more than that and it makes it easier to use a function in this case. |
With regards to the original post, your use of
$GLOBALS was incorrect. The correction would be unset($GLOBALS['myArray'][$i]);Quote:
$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)). |
Thank you very much. :) That not only fixed the problem, your explanation cleared up some other problems I been fighting with.
|
| All times are GMT. The time now is 01:10 AM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0