W3docs

get_defined_vars()

The get_defined_vars() function is a built-in function in PHP that returns an associative array containing all the defined variables in the current scope,

Introduction

The get_defined_vars() function is a built-in function in PHP that returns an associative array containing all the defined variables in the current scope, including those defined by PHP and those defined by the user.

Syntax

The syntax of the get_defined_vars() function is as follows:

The PHP syntax of the get_defined_vars()

array get_defined_vars(void)

The function takes no parameters. It returns an associative array where the keys are the variable names and the values are the variable values.

Example Usage

Here is an example of how to use the get_defined_vars() function in PHP:

Example of PHP get_defined_vars()

<?php
$var1 = "hello";
$var2 = 42;
function testFunction() {
  $var3 = true;
  $all_vars = get_defined_vars();
  print_r($all_vars);
}
testFunction();
?>

In this example, we define two global variables $var1 and $var2, and one local variable $var3 inside testFunction(). When get_defined_vars() is called inside the function, it only returns the local variables and PHP superglobals, not the global $var1 and $var2. The output shows an associative array containing the current scope's variables:

Array
(
    [var3] => 1
    [GLOBALS] => Array
        (
            ...
        )
    [$_SERVER] => Array
        (
            ...
        )
    [$_GET] => Array
        (
            ...
        )
    [$_POST] => Array
        (
            ...
        )
    [$_FILES] => Array
        (
            ...
        )
    [$_COOKIE] => Array
        (
            ...
        )
    [$_SESSION] => Array
        (
            ...
        )
)

Note: This function has been available since PHP 4.0.5. It always includes PHP superglobals in the returned array, regardless of the current scope.

Conclusion

The get_defined_vars() function is a useful tool for inspecting all the defined variables in the current scope of a PHP script. It can be used for debugging purposes, to check if a particular variable has been defined, or to ensure that all necessary variables have been defined before executing a block of code. By using this function, developers can quickly verify the current state of variables and debug scope-related issues without manually checking each one.

Practice

Practice

What does the PHP function get_defined_vars() do?