Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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

This comment has been minimized.

Copy link
Owner Author

@groovenectar groovenectar commented Apr 30, 2015

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