Below is a function (part of a procedurally written Wordpress plugin) which iterates through a multi dimensional array of regions, adding them to a custom hierarchical taxonomy. In the spirit of globals are generally bad practice I'd like to see how one could achieve the same ends without one.The function calls upon itself as it iterates through the array. The global in question is $last_region which does not appear anywhere else in the application but here, hence my desire to see if it can be avoided. It previously had been defined just prior to the function, but I found this was unnecessary, as defining it within the function itself was sufficient. I assume this is because once the function has run once, it has been created in memory, and therefore exists for subsequent iterations.If I understand the loop correctly here, global $last_region fires the function $last_region = wp_insert_term($name, 'test', array('slug' => $slug, 'parent' => $parent_id));, which creates the taxonomy entry for WordPress. I must admit I'm a bit unclear on how this string now stored in $last_region enables the function to operate on its next loop.function do_insert_region($regions= array(), $parent_id = 0){    global $last_region;    foreach ($regions as $slug => $name) {        if (is_array($name) && $slug != 'child') {            do_insert_region($name, $parent_id);        } else {            if ($slug == 'child') {                do_insert_region($name, $last_region['term_id']);            } else {                $last_region = wp_insert_term($name, 'test', array('slug' => $slug, 'parent' => $parent_id));            }        } //if(is array and not child)    } //foreach}Where $region = get_regions(); which returns an array like this one.
Foreach with the aim of removing the need for a $global
php;wordpress