php

How to print all defined variables and values in PHP

In this tutorial, we’re going to see how all variables can be displayed in PHP without having to know their names.
 

get_defined_vars()

The currently defined variables can be determined using get_defined_vars(). The function returns an array which contains the name of the variable as a key and its content as a value (variable name => variable content). The best thing to do is to simply output this array via var_dump().

<?php
    $a = 555;
    var_dump(get_defined_vars());
?>

Output:

array(5) {
  ["_GET"]=>
  array(0) {
  }
  ["_POST"]=>
  array(0) {
  }
  ["_COOKIE"]=>
  array(0) {
  }
  ["_FILES"]=>
  array(0) {
  }
  ["a"]=>
  int(555)
}
 

get_defined_vars() and global variables / Superglobals

If get_defined_vars() is called at the top level, the returned array also contains the superglobals. When get_defined_vars() is called in the scope of a function, these are no longer part of the return, although they can be accessed from within the function.

<?php
    function myfunction() {
        $b = 222;
         
        var_dump(get_defined_vars());
    }
 
    $a = 555;
    myfunction();
?>

Output:

array(1) {
  ["b"]=>
  int(222)
}

As you can see, all other global variables are missing, too. Only if these are explicitly “imported” in the scope of the function using the keyword “global”, they are returned by get_defined_vars(). As can be seen in the following example, however, the global variable is not really “imported”. Instead, it is a reference to it, which makes no difference in practice.

<?php
    function myfunction() {
        global $a;
        global $_POST;  // Applying global to a superglobal does not generate an error,
                 // It is still not included in the return of get_defined_vars().
        $b = 222;
         
        // to compare $d with reference to $c
        $c = 999;
        $d =& $c;
         
        var_dump(get_defined_vars());
    }
 
    $a = 555;
    myfunction();
?>

Output:

array(4) {
  ["a"]=>
  &int(555)
  ["b"]=>
  int(222)
  ["c"]=>
  &int(999)
  ["d"]=>
  &int(999)
}
PHP MCQ - Multiple Choice Questions and AnswersPHP Questions and Answers – Object-Oriented OOP – Part 1This collection of PHP Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Object-Oriented OOP”.   1. The concept of…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *