Last active
August 29, 2015 14:20
-
-
Save groovenectar/ed2ff9852acc77f8b894 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test array:
Call: