How to format var_export to php5.4 array syntax

designermonkey picture designermonkey · Jun 19, 2014 · Viewed 10.5k times · Source

There are lots of questions and answers around the subject of valid php syntax from var outputs, what I am looking for is a quick and clean way of getting the output of var_export to use valid php5.4 array syntax.

Given

$arr = [
    'key' => 'value',
    'mushroom' => [
        'badger' => 1
    ]
];


var_export($arr);

outputs

array (
  'key' => 'value',
  'mushroom' => 
  array (
    'badger' => 1,
  ),
)

Is there any quick and easy way to have it output the array as defined, using square bracket syntax?

[
    'key' => 'value',
    'mushroom' => [
        'badger' => 1
    ]
]

Is the general consensus to use regex parsing? If so, has anyone come across a decent regular expression? The value level contents of the arrays I will use will all be scalar and array, no objects or classes.

Answer

mario picture mario · Jun 19, 2014

I had something similar laying around.

function var_export54($var, $indent="") {
    switch (gettype($var)) {
        case "string":
            return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
        case "array":
            $indexed = array_keys($var) === range(0, count($var) - 1);
            $r = [];
            foreach ($var as $key => $value) {
                $r[] = "$indent    "
                     . ($indexed ? "" : var_export54($key) . " => ")
                     . var_export54($value, "$indent    ");
            }
            return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
        case "boolean":
            return $var ? "TRUE" : "FALSE";
        default:
            return var_export($var, TRUE);
    }
}

It's not overly pretty, but maybe sufficient for your case.

Any but the specified types are handled by the regular var_export. Thus for single-quoted strings, just comment out the string case.