Search code examples
phparraysscopeglobal-variablesglobal

How to move all array elements up to global scope in PHP?


I have a function in PHP which returns an array:

$Function_Returned_Array = array(

  ['Array_1'] => array('Element1', 'Element2', 'Element3'),
  ['Array_2'] => array('Element4', 'Element5', 'Element6'),
  ['Array_3'] => array('Element7', 'Element8', 'Element9')
);

But what I really need in the global scope is three separate arrays:

  $Array_1 = array('Element1', 'Element2', 'Element3');
  $Array_2 = array('Element4', 'Element5', 'Element6');
  $Array_3 = array('Element7', 'Element8', 'Element9');

This is so that in the Global Scope, I don't need to call:

$Function_Returned_Array['Array_1']

But I can call instead:

$Array_1

How can I move all the array elements up to global scope?


Solution

  • As I noted in the comment, PHP does have a function that will do exactly that:

    $Function_Returned_Array = array(
      'Array_1' => array('Element1', 'Element2', 'Element3'),
      'Array_2' => array('Element4', 'Element5', 'Element6'),
      'Array_3' => array('Element7', 'Element8', 'Element9')
    );
    
    extract($Function_Returned_Array);
    print_r($Array_1); //Works
    

    However with lack of context I must point out that there are some notable caveats with this solution:

    1. You risk overwriting other variables with the same name. PHP will not warn or otherwise notify you this is happening. For example, consider the following code:
    function saveData() {
         $isAuthenticated = $_SESSION['user'];
         extract($_POST);
         if (!$isAuthenticated) {
            return false;
         }
         // Save data
    }
    

    The problem here is if someone sends isAuthenticated as part of the request payload which will overwrite your own variable.

    1. Most IDEs will not know about the existence of those variables which will result in losing any completion help and often getting warnings of undefined variables.