Follow this Blog!

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:
unset($siteMapEntries);
$siteMapEntries = array();
Read on to see the solution.

Solution

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

unset($GLOBALS['siteMapEntries']);

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

$siteMapEntries = array();

function deleteSiteMapEntries(){
 unset($GLOBALS['siteMapEntries']);
 global $siteMapEntries;
 $siteMapEntries = array();
}

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

addASiteMapEntry('http://www.chtoen.com/','1.0');
echo "size before: ".count($siteMapEntries)."<br/>";
deleteSiteMapEntries();
echo "size after: ".count($siteMapEntries)."<br/>";

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