Skip to content

Instantly share code, notes, and snippets.

@isaac-gros
Last active June 12, 2020 07:35
Show Gist options
  • Save isaac-gros/6bdd6eb33fbf3ee5d41b7e74136cbc5e to your computer and use it in GitHub Desktop.
Save isaac-gros/6bdd6eb33fbf3ee5d41b7e74136cbc5e to your computer and use it in GitHub Desktop.
Write an array as a string in PHP.
<?php
/**
* NOTICE
* This code was made to write simple and multi-dimensional arrays in .php files.
* It print a whole array as a string and it keeps the exact structure given.
* You can use file_put_contents() and pass the output as the 2nd parameter
* to have a clean PHP array written in the file of your choice.
*/
/**
* Write an array as a string.
*
* @author Isaac Gros
*
* @param Array $array : The array to convert. Required.
* @param Int $indent_size : The indent size. Required.
* @param Array $checked_keys : The keys already parsed. Not required.
* @param Int $base_indent : The base indent size to keep the same level on each dimension. Not required.
* @return String
*/
function array_as_string($array, $indent_size, $checked_keys = [], $base_indent = null) {
// Output string of an array.
// Always begin with an opening bracket.
$output = "[\r\n";
// Define the code indent parameters
$base_indent = (!isset($base_indent)) ? $indent_size : $base_indent;
$indent_char = str_repeat(" ", $indent_size);
// Loop on values of the array
foreach($array as $key => $value) {
// Check if there is a next value
$has_next = (next($array) !== false) ? : key($array) !== null;
// To prevent repetitions of keys, check if
// the current index has not already been checked.
// Check also if the index is equal to 0 to keep it.
if(!in_array($key, $checked_keys) || $key == 0) {
// If the index checked is an array, repeat this function
// and include the checked keys array.
if(is_array($value)) {
array_push($checked_keys, $key);
// Convert key to the right type
$key = (is_string($key)) ? "'$key'" : $key;
// Begin a new array
$output .= $indent_char . "$key => ";
$output .= arrayToString($value, $indent_size + $base_indent, $checked_keys, $base_indent);
} else {
// Convert key and value to the right type
$key = (is_string($key)) ? "'$key'" : $key;
// Print the key and value
$value = (is_string($value)) ? "'$value'" : $value;
$output .= $indent_char . "$key => $value";
}
}
// If there is another element next, add a coma
if($has_next) {
$output .= ",\r\n";
} else {
// Close the array by removing extra indent
$output .= "\r\n" . substr($indent_char, $base_indent) . "]";
}
}
return $output;
}
// Example array
$array = [
'firstname' => 'John',
'lastname' => 'Doe',
'address' => [
'line_1' => '123 Main St',
'line_2' => '',
'city' => 'Beverly Hills, CA',
'zip_code' => '90210'
]
];
echo '$var = ' . array_as_string($array, 4) . ';';
// Result :
// $var = [
// 'firstname' => 'John',
// 'lastname' => 'Doe',
// 'address' => [ ... ]
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment