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:
1unset($siteMapEntries);
2$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:
01<?php
02 
03$siteMapEntries = array();
04 
05function deleteSiteMapEntries(){
06 unset($GLOBALS['siteMapEntries']);
07 global $siteMapEntries;
08 $siteMapEntries = array();
09}
10 
11function addASiteMapEntry($loc, $priority){
12 global $siteMapEntries;
13  
14 $siteMapEntries[] = array(
15  'loc' => $loc,
16  'priority' => $priority
17 );
18}
19 
20addASiteMapEntry('http://www.chtoen.com/','1.0');
21echo "size before: ".count($siteMapEntries)."<br/>";
22deleteSiteMapEntries();
23echo "size after: ".count($siteMapEntries)."<br/>";
24 
25?>
Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael