Get variable definition as string

Is there a built-in way to get array definition in string format? The output must be valid PHP code to define the same array.

For instance:

$arrayDefinition = array_encode($anArray);

Should return something like:

['a' => 'x', 'b' => 'y']
+4
source share
3 answers

I think what you are looking for var_export().

Example:

$arr = [1,2,3];
echo $str = var_export($arr, TRUE);

output:

array ( 0 => 1, 1 => 2, 2 => 3, )
+10
source

Not sure if this is useful to you, but found from http://php.net/manual/en/function.var-dump.php#77234

 <?php
    echo '<pre>'; // This is for correct handling of newlines
    ob_start();
    var_dump($var);
    $a=ob_get_contents();
    ob_end_clean();
    echo htmlspecialchars($a,ENT_QUOTES); // Escape every HTML special chars (especially > and < )
    echo '</pre>';
    ?>
+1
source

var_export - Prints or returns a syntax string representation of a variable You also link to http://php.net/manual/en/function.var-export.php

<?php
var_export(array (1, 2, array ("a", "b", "c")));
?>

This will be output as follows:

array ( 0 => 1, 1 => 2, 2 => array ( 0 => 'a', 1 => 'b', 2 => 'c', ), )
0
source

All Articles