How to Use get_defined_vars() Function in PHP

The get_defined_vars() is a useful function in PHP used to retrieve an array of all defined variables in the current scope including those defined in the global scope. With get_defined_vars(), you can easily get a list of all the variables in your PHP script, which can be useful for debugging or analyzing your code.

It produces an array with all the presently defined variables and their values inside the local scope. Developers may learn more about the variable environment during runtime since it gives a snapshot of the variable state at the point of execution.

Syntax for PHP get_defined_vars() Function

The get_defined_vars() function in PHP follows the simple syntax given below:

This function does not take any parameters. When called, it returns an associative array containing all the currently defined variables and their respective values within the local scope.

How to Use get_defined_vars() Function in PHP?

In PHP, get_defined_vars() function has the following use cases:

Example 1

The basic usage of get_defined_vars() allows you to retrieve all the defined variables in the current scope. By calling get_defined_vars(), you can obtain an associative array containing all the variable names and their corresponding values within the local scope.

For example, if you want to get a list of all the variables in a script, you can do the following:


function myFunction() {

$str1 = "Linux";

$str2 = "Hint";

$grabVars = get_defined_vars();





In the above code myFunction() is defined which has 2 variables $str1 and $str2. After that $grabVars variable is declared with get_defined_vars() function to grab all the defined functions in the current scope.

It is important to note that get_defined_vars() only works within the current scope, meaning that it will only retrieve variables that are defined within the current function or file. If you need to get variables from another scope, you will need to use a different PHP function, such as the global keyword or the $_GLOBALS superglobal.

Example 2


$var1 = 10;

$var2 = "Hello, Linuxhint!";

function myFunction() {

$var3 = 18;

$var4 = "Linux";

$definedVars = get_defined_vars();





In the above example, code 2 variables are declared out of the function and two are inside the myFunction(). As get_defined_vars() only retrieves the variables which are in the current scope, therefore, it will only print $var3 and $var4.


The get_defined_vars() function is a useful PHP function that can help in debugging situations by retrieving all the currently defined variables in a script. Simply call the function within your script to use it. This article offered a thorough tutorial with examples of how to utilize the PHP get_defined_vars() function.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.