Skip to content

Instantly share code, notes, and snippets.

@groovenectar
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groovenectar/ed2ff9852acc77f8b894 to your computer and use it in GitHub Desktop.
Save groovenectar/ed2ff9852acc77f8b894 to your computer and use it in GitHub Desktop.
<?php
/*
* Formats an array so that it can be copied and pasted directly as a PHP variable
*
* $arr => The input array
* $varname => Optional. Example, '$foo' will prefix return with '$foo = '
* $output => 'pre' (default) outputs with a <pre> tag. true outputs, false returns a string
* $recursing => Used internally for recursion
*/
function php_array_variable($arr, $varname = null, $output = 'pre', $recursing = 0) {
$formatted = '';
if (!$recursing) {
if ($output === 'pre') {
$formatted .= '<pre>';
}
if ($varname) {
$formatted .= $varname . ' = ';
}
}
if (gettype($arr) === 'array') {
$formatted .= '[' . "\n";
foreach ($arr as $key => $val) {
$formatted .= str_repeat("\t", ($recursing + 1));
if (is_integer($key)) {
$formatted .= $key;
} else {
$formatted .= "'" . $key . "'";
}
$formatted .= ' => ';
if (gettype($val) === 'array') {
// If the recursion returns an error, return false (error) for the whole call
if (($tmp = php_array_variable($val, null, false, $recursing + 1)) === false) {
return false;
}
$formatted .= $tmp;
} else if (is_numeric($val)) {
$formatted .= $val;
} else if (is_bool($val)) {
$formatted .= $val ? 'true' : 'false';
} else if (is_null($val)) {
$formatted .= 'null';
} else if (gettype($val) !== 'object') {
$formatted .= "'" . str_replace('\'', '\\\'', $val) . "'";
} else {
// Return false (error) if object encountered
return false;
}
$formatted .= ',' . "\n";
}
$formatted .= str_repeat("\t", $recursing) . ']';
} else {
// $arr must be an array, return false (error) if not
return false;
}
if ($recursing) {
return $formatted;
}
$formatted .= ';';
if ($output === 'pre') {
$formatted .= "\n" . '</pre>';
}
if ($output) {
echo $formatted;
return true;
} else {
return $formatted;
}
}
@groovenectar
Copy link
Author

Test array:

$test = [
    1 => 'test',
    'two' => 'test2',
    4 => [
        'key' => true,
        'key2' => 2.2,
    ],
    5 => 'test3',
    6 => [
        'key3' => null,
        'key4' => [
            'key5' => 'value4',
            'key6' => 'value5',
        ],
    ],
];

Call:

php_array_variable($test, '$test');

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