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?
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:
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.