There are functions in PHP that display structured information about a variable, be it an object, an array, a string, or any PHP data type at all. Some of these commonly used function are:
var_dump()
functionprint_r()
functionvar_export()
function.You can click on the first two links to learn more about them from previous shots. In this shot, we’ll discuss the var_export()
function.
The var_export() function has similarities with var_dump()
because they both get structured information about variables. But where var_export()
can return this information in a form that can be parsed by the PHP parser in computations, var_dump()
cannot. In clearer terms, the return value of var_export()
function can be used in further computations, unlike var_dump
.
var_export($variable, $return = false)
$variable
: This is the variable, of any data type, whose value is to be returned or displayed.$return
: This is a Boolean parameter, which is false
by default and is optional. If set as true
, it causes the function to return the value of the variable that was passed but not display it.This function will return null
if the $return
parameter is not set as true
, in which case the variable is displayed. If it is set as true
, the function will return the structured representation of the variable and no screen display.
In the snippet below, two variables, $my_int
and $my_array
, are set and their values exported. In one of the var_export
functions, the return
parameter is not set — i.e., it defaults to false
— and in the other, it is set as true
. This causes the first function to have an output, while the second function, with its return
set to true
, gives no output. This can be seen in the output when we execute the code below.
<?php// an integer value$my_int =24;// an array value$my_array = array ("a", "b", "c");// exporting this valuesvar_export($my_array);echo "\n";// no display because return is set as truevar_export($my_int,true) ;?>
<?php// initialize an integer variable$my_int = 3.1;// store the output of var_export on the variable$value1 = var_export($my_int, true);// store the output of var_export on the variable$value2 = var_dump($my_int);// do some computation with the stored values and echoecho $value1 + 50;echo "\n";echo $value2 + 90;?>
In the code above, we have tried to clarify the difference between var_export
and var_dump
functions. It is obvious from the output of the code above that the result of the var_export
function can be used in further computations, but that is not possible with the results from the var_dump
function.
var_export
function, unlike the var_dump
function, won’t return the data type of the passed variable.