Skip to content

Instantly share code, notes, and snippets.

@Bogdaan
Created September 10, 2018 12:31
Show Gist options
  • Save Bogdaan/ffa287f77568fcbb4cffa0082e954022 to your computer and use it in GitHub Desktop.
Save Bogdaan/ffa287f77568fcbb4cffa0082e954022 to your computer and use it in GitHub Desktop.
PHP var_export() with short array syntax (square brackets) indented 4 spaces
<?php
function varexport($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;
}
@dahse89
Copy link

dahse89 commented Sep 1, 2022

Thanks, worked for me :)

@SDIjeremy
Copy link

any ways to remove the keys if array is_list?

@vladlu
Copy link

vladlu commented May 1, 2023

It doesn't work for nested arrays. Use this one:

function shorthand_var_export($expression, $return=false) {
    $export = var_export($expression, true);
    $patterns = [
        "/array \(/" => '[',
        "/^([ ]*)\)(,?)$/m" => '$1]$2',
    ];
    $output = preg_replace(array_keys($patterns), array_values($patterns), $export);
    if ($return) {
        return $output;
    } else {
        echo $output;
    }
}

$myArray = array('foo' => 'bar', 'baz');
shorthand_var_export($myArray);

@cweiske
Copy link

cweiske commented Apr 26, 2024

Empty objects in PHP 8.0.30 at least are var_exported as

array (
  'key' => 
  (object) array(
  ),
)

This syntax is not handled correctly by this script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment