Get all of the defined variables - their names and values - with one function call. The result will be a multidimensional array with the variable names as keys.

Which variables you get back depends on the scope you’re in. If you call this function from within another function, you’ll only get the variables defined for that function you are currently in.

While in the global scope, you’ll get back $GLOBALS, $_POST, $_GET, $_COOKIES, and all the other superglobals as well as any user declared variables.

Note: You’ll only get the variables that were set before this function was called. It doesn’t look for all the variables in the file, just what PHP has to work with at the point of calling get_defined_vars().

Also note for these examples, I’ll be using the var_dump() output which will look different from the previous examples on this site.

In this first example we see that only three variables “existed” in the scope of that function. $a and $b were defined before calling it but were outside its scope.

function getSomeVars( $test, $thing ) {
  $q    = 'monkey';
  $vars = get_defined_vars();
 
  return $vars;
}
 
$a    = 'apple';
$b    = 'banana';
$vars = getSomeVars($a, $b);
/*
array(3) {
  ["test"]=>
  string(5) "apple"
  ["thing"]=>
  string(6) "banana"
  ["q"]=>
  string(6) "monkey"
}
*/

If we define $q after calling get_defined_vars() it doesn’t show in the resulting array.

function getSomeVars( $test, $thing ) {
  $vars = get_defined_vars();
  $q    = 'monkey';
 
  return $vars;
}
 
$a    = 'apple';
$b    = 'banana';
$vars = getSomeVars($a, $b);
/*
array(2) {
  ["test"]=>
  string(5) "apple"
  ["thing"]=>
  string(6) "banana"
}
*/

Using unset() on a variable removes it from the “defined vars” list.

function getSomeVars( $test, $thing ) {
  unset($thing);
  $vars = get_defined_vars();
 
  return $vars;
}
 
$a    = 'apple';
$b    = 'banana';
$vars = getSomeVars($a, $b);
/*
array(1) {
  ["test"]=>
  string(5) "apple"
}
*/

Referenced variables are also by referenced in the array get_defined_vars() gives you. You can see this in the resulting value for $vars['test'] and also by the & shown in the var_dump –> &string(6) “monkey”

function getSomeVars( &$test, $thing ) {
  $vars = get_defined_vars();
  $test = 'zebra';
 
  return $vars;
}
 
$a    = 'apple';
$b    = 'banana';
$vars = getSomeVars($a, $b);
/*
array(2) {
  ["test"]=>
  &string(6) "monkey"
  ["thing"]=>
  string(6) "banana"
}
*/