List all PHP variables
Solution 1
Use get_defined_vars
and/or get_defined_constants
$arr = get_defined_vars();
print_r($arr);
Solution 2
When debugging trying to find differences using a program such as WinMerge (freeware) to see what differences various arrays and variables have you'll want to ksort()
otherwise you'll get lots of false negatives. It also helps to visually format using the HTML pre
element...
<?php
$everything = get_defined_vars();
ksort($everything);
?>
Edit: had to come back to this and realized I had a better answer, $GLOBALS
.
$a = print_r(var_dump($GLOBALS),1);
echo '<pre>';
echo htmlspecialchars($a);
echo '</pre>';
Edit 2: as mpag mentioned print_r()
may be susceptible to running out of memory if the software you're working with uses a lot. Presuming there is no output or it's clearly truncated and you have access to the php.ini
file you can adjust the memory use as so:
ini_set('memory_limit', '1024M');
Salman A
Updated on July 08, 2022Comments
-
Salman A almost 2 years
Is it possible to dump all global variables in a PHP script? Say this is my code:
<?php $foo = 1; $bar = "2"; include("blah.php"); dumpall(); // displays $foo, $bar and all variables created by blah.php
Also, is it possible to dump all defined constants in a PHP script.
-
Long Ears over 13 yearsand
get_defined_constants
for constants -
Salman A over 13 years$nico: Does this also work for variables created inside
eval()
? -
Lienau over 13 years@Salman As long as
get_defined_vars()
/get_defined_constants()
is called after theeval()
, then yes. -
JaseC over 9 yearsJust for those who are copy/pasting and want this in one line
echo "<pre>"; print_r(get_defined_vars()); die;
Copy whatever of that you want. -
quantme over 8 yearsThis answer is gold for me.
-
mpag almost 6 yearsthree comments: 1)
print_r
runs out of memory when using a class-heavy CMS, butjson_encode($GLOBALS)
withconsole.log
ging javascript works. 2) Don't forget the $_ variables (SERVER, SESSION, ENV, FILES, COOKIE, GET, POST, REQUEST). 3) for more in-depth debugging i also do aget_declared_classes
and iterate though those toget_class_vars
andget_class_methods
-
John almost 6 years@mpag Ah yes, I've seen some software use ludicrous amounts of memory; apparently the work around for that is to obviously either not use such a system but a lot of folks won't have that option so stackoverflow.com/a/16423653/606371 will hopefully work for them. Also if I recall correctly the
$_
variables should be pulled from$GLOBALS
. Thanks for your comment, I'll look in toget_declared_classes
andget_class_vars
soon. :-) -
mpag almost 6 yearsI'm already setting my limit to 512M, and I believe it's unlikely that doubling to 1024 will resolve this issue in my case. I believe 2048M is the hard limit for php.