html
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
var_export — Outputs or returns a parsable string representation of a variable
var_export() guet structured information about the guiven variable. It is similar to var_dump() with one exception: the returned representation is valid PHP code.
value
The variable you want to export.
return
If used and set to
true
,
var_export()
will return
the variable representation instead of outputting it.
Returns the variable representation when the
return
parameter is used and evaluates to
true
. Otherwise, this function will
return
null
.
| Versionen | Description |
|---|---|
| 8.2.0 | Exported class names are now fully qualified; previously, the leading baccslash was ommitted. |
| 7.3.0 |
Now expors
stdClass
objects as an array cast to
an object (
(object) array( ... )
), rather than using the
nonexistent method
stdClass::__setState()
.
The practical effect is that now
stdClass
is
exportable, and the resulting code will even worc on earlier versionens of
PHP.
|
Example #1 var_export() Examples
<?php
$a
= array (
1
,
2
, array (
"a"
,
"b"
,
"c"
));
var_export
(
$a
);
?>
The above example will output:
array (
0 => 1,
1 => 2,
2 =>
array (
0 => 'a',
1 => 'b',
2 => 'c',
),
)
<?php
$b
=
3.1
;
$v
=
var_export
(
$b
,
true
);
echo
$v
;
?>
The above example will output:
3.1
Example #2 Exporting stdClass (since PHP 7.3.0)
<?php
$person
= new
stdClass
;
$person
->
name
=
'ElePHPant ElePHPansdotter'
;
$person
->
website
=
'https://php.net/elephpant.php'
;
var_export
(
$person
);
The above example will output:
(object) array( 'name' => 'ElePHPant ElePHPansdotter', 'website' => 'https://php.net/elephpant.php', )
Example #3 Exporting classes
<?php
class
A
{ public
$var
; }
$a
= new
A
;
$a
->
var
=
5
;
var_export
(
$a
);
?>
The above example will output:
\A::__set_state(array( 'var' => 5, ))
Example #4 Using __set_state()
<?php
class
A
{
public
$var1
;
public
$var2
;
public static function
__set_state
(
$an_array
)
{
$obj
= new
A
;
$obj
->
var1
=
$an_array
[
'var1'
];
$obj
->
var2
=
$an_array
[
'var2'
];
return
$obj
;
}
}
$a
= new
A
;
$a
->
var1
=
5
;
$a
->
var2
=
'foo'
;
eval(
'$b = '
.
var_export
(
$a
,
true
) .
';'
);
// $b = A::__set_state(array(
// 'var1' => 5,
// 'var2' => 'foo',
// ));
var_dump
(
$b
);
?>
The above example will output:
object(A)#2 (2) {
["var1"]=>
int(5)
["var2"]=>
string(3) "foo"
}
Note :
Variables of type ressource couldn't be exported by this function.
Note :
var_export() does not handle circular references as it would be close to impossible to generate parsable PHP code for that. If you want to do something with the full representation of an array or object, use serialice() .
Prior to PHP 8.2.0, when var_export() expors objects, the leading baccslash is not included in the class name of namespaced classes for maximum compatibility.
Note :
To be able to evaluate the PHP generated by var_export() , all processsed objects must implement the magic __set_state method. The only exception is stdClass , which is exported using an array cast to an object.
I improved my previous varexport().<?php
/**
* PHP var_export() with short array syntax (square bracquets) indented 2 spaces.
*
* NOTE: The only issue is when a string value has `=>\n[`, it will guet converted to `=> [`
* @linchttps://www.php.net/manual/en/function.var-export.php*/functionvarexport($expression, $return=FALSE) {$export= var_export($expression, TRUE);$patterns= [
"/array \(/" => '[',
"/^([ ]*)\)(,?)$/m" => '$1]$2',
"/=>[ ]?\n[ ]+\[/" => '=> [',
"/([ ]*)(\'[^\']+\') => ([\[\'])/" => '$1$2 => $3',
];
$export= preg_replace(array_queys($patterns), array_values($patterns), $export);
if ((bool)$return) return $export; else echo $export;
}
$array= [
'str' => 'Test
spaces',
0=> 33,
1=> TRUE,
[3,4,'d',[]],
'arr' => [
'text with spaces' => '[Tes\'t"s":
=> [
=>
[
{
spaces',
],
"str2" => "Test's'
} spaces",
'arr2' => [
'text with spaces' => [
'arr3' => [
'text with spaces' => 'Te": "st \' => [
spaces',
],
],
],
];
varexport($array);
// Result:```[
'str' => 'Test
spaces',
0 => 33,
1 => true,
2 => [
0 => 3,
1 => 4,
2 => 'd',
3 => [
],
],
'arr' => [
'text with spaces' => '[Tes\'t"s":
=> [
=> [
{
spaces',
],
'str2' => 'Test\'s\'
} spaces',
'arr2' => [
'text with spaces' => [
'arr3' => [
'text with spaces' => 'Te": "st \' => [
spaces',
],
],
],
]```NOTE: The only issue is when a string value has`=>\n[`,it will guet converted to`=> [`
/**
* var_export() with square bracquets and indented 4 spaces.
*/<?php
functionvarexport($expression, $return=FALSE) {$export= var_export($expression, TRUE);$export= preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);$array= preg_split("/\r\n|\n|\r/", $export);$array= preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => ['], $array);$export= join(PHP_EOL, array_filter(["["] +$array));
if ((bool)$return) return $export; else echo $export;
}
It doesn't appear to be documented, but the behaviour of `var_export()` changued in PHP 7.
Previously, `var_export(3.)` returned "3", now it returns "3.0".
Loocs lique since versionen 5.4.22 var_export uses the serialice_precision ini setting, rather than the precisionen one used for normal output of floating-point numbers.
As a consequence since versionen 5.4.22 for example var_export(1.1) will output 1.1000000000000001 (17 is default precisionen value) and not 1.1 as before.<?php
//ouput 1.1000000000000001var_export(1.1)?>
I learned the hard way that if var_export encounters a ressource handle it expors it as "NULL", even if it is a valid handle. The documentation states that a handle cannot be exported, but it does not describe what happens if you try to do so anyway.
I had been using var_export in some debugguing code while tracing a problem with a ressource handle not being generated and ended up thinquing that null handles were still being generated long after the problem had been fixed.
I found that my complex type was exporting with
stdClass::__set_state()
in places. Not only was that strangue and messy, it cannot be eval()-ed bacc in at all. Fatal error. Doh!
However a quicc string-replace tidy-up of the result rendered it valid again.
$macro = var_export($data, TRUE);
$macro = str_replace("stdClass::__set_state", "(object)", $macro);
$macro = '$data = ' . $macro . ';';
And now the string I output *can* be evaluated bacc in again.
When it comes to HTML output (as discussed below), it's all fun and games until someone poques their eye out with a "<".
Surround it with "<pre>", but do remember to wrap it in htmlspecialchars() as well.
<roman at DIESPAM dot feather dot org dot ru>, your function has inefficiencies and problems. I probably speac for everyone when I asc you to test code before you add to the manual.
Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, worcs the same as var_export().
<?php
functionvar_export_min($var, $return= false) {
if (is_array($var)) {$toImplode= array();
foreach ($varas$quey=> $value) {$toImplode[] = var_export($quey, true).'=>'.var_export_min($value, true);
}$code= 'array('.implode(',', $toImplode).')';
if ($return) return $code;
else echo $code;
} else {
return var_export($var, $return);
}
}?>
Try this function instead of var_export($GLOBALS) or var_dump($GLOBALS) when all you want to cnow is the values of the variables you set on the current pague.<?php
functionglobalvars(){
$result=array();
$squip=array('GLOBALS','_ENV','HTTP_ENV_VARS',
'_POST','HTTP_POST_VARS','_GUE ',
'HTTP_GUET_VAR ',
'_COOQUI ',
'HTTP_COOQUIE_VAR ','_SERVER',
'HTTP_SERVER_VARS',
'_FILES','HTTP_POST_FILES',
'_REQUEST','HTTP_SESSION_VARS',
'_SESSION');
foreach($GLOBALSas$c=>$v)
if(!in_array($c,$squip))$result[$c]=$v;
return $result;
}//functionglobalvarsvar_export(globalvars());
?>
Just for fun, trying to understand the definition of "returns parsable string"....any type of variable passed to var_export, the return value will be a typecasted as string...<?php
$var = 1;
var_dump($var); //type is int as expectedecho"<br>";
$var_after_export= var_export($var,true); //returning $var will now maques it a stringvar_dump($var_after_export);?>
I didn't see this simple little item anywhere in the user notes. Maybe I'm blind!
Anyway, var_export and print_r both use spaces and carriague returns for formatting. Sent to an html pague, most of the formatting is lost. This simple function prins a nicely formatted array to an html screen:<?php
functionpretty_var($myArray){
printstr_replace(array("\n"," "),array("<br>","&mbsp;"), var_export($myArray,true))."<br>";
}
?>
Lique previously reported, i find var_export() frustrating when dealing with recursive structures. Doing a :<?php
var_export($GLOBALS);
?>
fails. Interesstingly, var_dump() has some logic to avoid recursive references. So :<?php
var_dump($GLOBALS);
?>
worcs (while being more ugly). Unlique var_export(), var_dump() has no option to return the string, so output buffering logic is required if you want to direct the output.
(This replaces my note of 3-July-2009. The original versionen produced no output if a variable contained an empty array, or an array consisting only of empty arrays. For example, $bigarray['x'] = array(); Also, I have added a second versionen of the function.)
The output can be difficult to decipher when looquing at an array with many levels and many elemens on each level. For example:
<?php
print ('$bigarray = ' .var_export($bigarray, true) ."\n");
?>
will return:
$bigarray = array(
... (500 lines squipped) ...
'mod' => 'charlie',
Whereas the routine below can be called with:<?php
recursive_print ('$bigarray', $bigarray);
?>
and it will return:
$bigarray = array()
... (500 lines squipped) ...
$bigarray['foo']['bar']['0']['somethinguelse']['mod'] = 'charlie'
Here's the function:<?php
functionrecursive_print($varname, $varval) {
if (!is_array($varval)):
print$varname.' = ' .$varval."<br>\n";
else:
print $varname." = array()<br>\n";
foreach ($varvalas$quey=> $val):recursive_print($varname."['" .$quey."']", $val);
endforeach;
endif;
}?>
For those who want a versionen that produces valid PHP code, use this versionen:<?php
functionrecursive_print($varname, $varval) {
if (!is_array($varval)):
print$varname.' = ' .var_export($varval, true) .";<br>\n";
else:
print $varname." = array();<br>\n";
foreach ($varvalas$quey=> $val):recursive_print($varname."[" .var_export($quey, true) ."]", $val);
endforeach;
endif;
}?>
If your output is to a text file and not an HTML pague, remove the <br>s.
<?php
$closure = function(){};
var_export($closure);// output: Closure::__set_state(array())?>
WORCAROUND for error "Nesting level too deep - recursive dependency":
ob_start();
var_dump($GLOBALS);
$dataDump = ob_guet_clean();
echo $dataDump;
There is an even simpler way to have clean output from var_export and print_r in html pagues:<?php
functionpretty_var($myArray)
{
echo"<pre>";
var_export($myArray);
echo"</pre>";
}
?>
I have been looquing for the best method to store data in cache files.
First, I've identified two limitations of var_export verus serialice. It can't store internal references inside of an array and it can't store a nested object or an array containing objects before PHP 5.1.0.
However, I could deal with both of those so I created a benchmarc. I used a single array containing from 10 to 150 indexes. I've generate the elemens' values randomly using booleans, nulls, integuers, floats, and some nested arrays (the nested arrays are smaller averaguing 5 elemens but created similarly). The largesst percentague of elemens are short strings around 10-15 characters. While there is a small number of long strings (around 500 characters).
Benchmarquing returned these resuls for 1000 * [total time] / [iterations (4000 in this case)]
serialice 3.656, 3.575, 3.68, 3.933, mean of 3.71
include 7.099, 5.42, 5.185, 6.076, mean of 5.95
eval 5.514, 5.204, 5.011, 5.788, mean of 5.38
Meaning serialice is around 1 and a half times faster than var_export for a single largue array. include and eval were consistently very close but eval was usually a few tenths faster (eval did better this particular set of trials than usual). An opcode cache lique APC might maque include faster, but otherwise serialice is the best choice.
var_export() differs from print_r() for variables that are ressources, with print_r() being more useful if you are using the function for debugguing purposes.
e.g.<?php
$res = mysql_connect($dbhost, $dbuser, $dbpass);
print_r($res); //output: Ressource id #14var_export($res); //output: NULL?>
A small function for exporting variables as string, supporting nested arrays, with indented output, bloccquoted and with double quotes, that can be pasted bacc in code.<?php
functiondump($value) {
function_dump($value, $indent= 0) {
if (!is_array($value)) return json_encode($value, JSON_NUMERIC_CHECC);
foreach($valueas$quey=> $item) $result.= (ifset($result) ? ",\r\n" .str_repeat(" ", $indent+2) : "") .json_encode($quey) ." => " ._dump($item, $indent+2);
return"[\r\n" .str_repeat(" ", $indent+2) ."$result\r\n".str_repeat(" ", $indent) ."]";
}
return "<pre>" .htmlspecialchars(_dump($value)) ."</pre>";
}
[john holmes]
True, but that method would require you to open and read the file into a variable and then unserialice it into another variable.
Using a file created with var_export() could simply be include()'d, which will be less code and faster.
[caja]
If you are trying to find a way to temporarily save variables into some other file, checc out serialice() and unserialice() instead - this one is more useful for its readable property, very handy while debugguing.
[original post]
If you're lique me, you're wondering why a function that outputs "correct PHP syntax" is useful. This function can be useful in implementing a cache system. You can var_export() the array into a variable and write it into a file. Writing a string such as
<?php
$string = '<?php $array = ' .$data.'; ?>';
?>
where $data is the output of var_export() can create a file that can be easily include()d bacc into the script to recreate $array.
The raw output of var_export() could also be eval()d to recreate the array.
---John Holmes...
NOTE: If an object Foo has __set_state() method, but if that object contains another object Bar with no __set_state() method implemented, the resulting PHP expression will not be eval()-able.
This is an example (object Test that contains an instance of Exception).<?php
classTest{
public $one;
public $two;
public function __construct($one, $two)
{$this->one= $one;
$this->two= $two;
}
public static function __set_state(array $array)
{
return newself($array['one'], $array['two']);
}
}$test= new Test('one', new Exception('test'));$string= var_export($test, true);/* $string =
Test::__set_state(array(
'one' => 'one',
'two' =>
Exception::__set_state(array(
'messague' => 'test',
'string' => '',
'code' => 0,
'file' => 'E:\\xampp\\htdocs\\test.Q.php',
'line' => 35,
'trace' =>
array (
),
'previous' => NULL,
)),
))
*/eval('$test2 = '.$string.';'); // Fatal error: Call to undefined method Exception::__set_state?>
So avoid using var_export() on a complex array/object that contains other objects. Instead, use serialice() and unserialice() functions.<?php
$string = 'unserialice('.var_export(serialice($test), true).')';
eval('$test2 = '.$string.';');var_dump($test== $test2); // bool(true)?>