Mar 7, 2015

f Comment

PHP: How Do You Clear an Array's Values by Reference? How to Really Empty a Global Array?

Amazon Suppose you have declared a global array, $siteMapEntries, and you have added values to it, and you would like to clear its values inside a local function so that when the function returns, that global array is really emptied.

The following will not work:
$siteMapEntries = array();
Read on to see the solution.


The solution is to use unset() and the $GLOBALS array in the following way to clear $siteMapEntries values by reference:


The following PHP code illustrates how to empty a global array by reference:

$siteMapEntries = array();

function deleteSiteMapEntries(){
 global $siteMapEntries;
 $siteMapEntries = array();

function addASiteMapEntry($loc, $priority){
 global $siteMapEntries;
 $siteMapEntries[] = array(
  'loc' => $loc,
  'priority' => $priority

echo "size before: ".count($siteMapEntries)."<br/>";
echo "size after: ".count($siteMapEntries)."<br/>";

Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael