Here’s a great way to turn an array into readable strings in PHP. For example, I want an error notice to be sent to me automatically when a database action in a function fails. The problem is, I cannot possibly know what is going to be in every form that is used in the function that generates the database query. While I *can* easily get the keys and values using
foreach ($in_array as $key => $value)
and building a string, what if the value itself is an array? The value for any array within the array would be “Array”. Not very useful!
Fortunately, PHP functions can be recursive. Here’s a function I wrote to handle that:
function getArrayAsString($in_array)
{
$string = '<br />';
foreach ($in_array as $key => $value)
{
if (is_array($value)) $string = $string.'<br /><strong>'.$key.'</strong>: '.getArrayAsString($value).'<br />';
else $string = $string.'<strong>'.$key.'</strong>: '.$value.'<br />';
}
return $string;
}
Each value is checked to see if it is an array. If it is, it (the array value) is sent to this function, and it processes until all of its values have been evaluated, sending any of those array values into this function as well.
I use this function by concatenating the result to an error message by calling the function with the $_POST variable as the array parameter. This way, I have my custom-built message specific to the failed function, and I get all the information that was posted so I can evaluate the error without having to generate the array values one at a time, or worrying if any values are themselves arrays. Click here to fill out a form and see how this recursive function works.
Personally, I like my “keys” to be bold and the values to be normal, but you can change that to suit your tastes.