Parse an Array as a String with PHP

Recently I found myself needing to quickly parse an associative array as a string to use in a logging function. I wanted minimal lines and to keep it simple. Using two PHP functions, http_build_query() and str_replace(), and a little fiddling I found my answer.

Of course, if you’re not using an associative array, you could always use the implode() function. To parse a simple array as a string using the implode function would look like this:

<?php
// Simple array //
$simple_array = array(
    'cat', 'mouse', 'dog', 'turtle', 'fish'
);

$simple_array_implode = implode(', ', $simple_array);

var_dump($simple_array_implode);
?>

// Simple array implode output //
string 'cat, mouse, dog, turtle, fish' (length=29)

Now, onto the associative arrays. Using the str_replace() and http_build_query() to parse the array is slightly more complex, but easy to use. Http_build_query takes the array and turns it into a query string to be used for URLs. This adds some unwanted characters for our purposes, which is why we use the str_replace function to clean up the output. See the following example.

<?php
// Simple associative array test //
$simple_assoc_array = array(
    'First Name' => 'Bob',
    'Last Name' => 'Doe',
    'Age' => 15,
    'Sex' => 'Male',
    'Height' => '6 Foot',
    'Location' => 'Georgia'
);

// More complex array //
$files_array = array(
    'name' => 'funny-picture.jpg',
    'type' => 'image/jpeg',
    'tmp_name' => 'C:\wamp\tmp\php998F.tmp',
    'error' => 0,
    'size' => 27006
);

// Convert to string //
$simple_assoc_array_to_string = str_replace(array('&', '=', '+'), array(', ', ': ', ' '), http_build_query($simple_assoc_array));
$files_array_to_string = str_replace(array('&', '=', '%2F', '%3A', '%5C'), array(', ', ':', '/', ':', '\\'), http_build_query($files_array));

// Output the conversions //
var_dump($simple_assoc_array_to_string);
var_dump($files_array_to_string);
?>

// Associative array output //
string 'First Name: Bob, Last Name: Doe, Age: 15, Sex: Male, Height: 6 Foot, Location: Georgia' (length=86)
string 'name:funny-picture.jpg, type:image/jpeg, tmp_name:C:\wamp\tmp\php998F.tmp, error:0, size:27006' (length=94)

When using the str_replace() function, I find it’s easier to use arrays for the delimiters; this way you can use multiple search and replace parameters. The thing that may get you, and you should remember, is that when using array, you should place your search and replace parameters in the same key index of the arrays. For instance, we wanted the “&” character replaced with “,”, so they both had to be at the 0 index of the array.

If you wanted to wrap this all up into a function so that you could change it on the fly easily, it could look something like this:

<?php
/**
 * Parses an associative array into a string.
 * @param array $array Array to parse
 * @return string 
 */
function parse_assoc_to_string($array) {
    // Params to search for //
    $search = array('&', '=', '+');
    // Replace with //
    $replace = array(', ', ': ', ' ');
    // Return String
    return str_replace($search, $replace, http_build_query($array));
}
?>

This is just a simple function, but you would probably want to filter the array. Using this function you could easily change what search and replace parameters you wanted to use, and do it on the fly if necessary.

For more information about these function, please visit the links:

If you would like a copy of everything that has been covered in this post, please download the file below. To use the file unpack it and place it in your root directory and just go to “localhost/parse_array/parse.php”.

This entry was posted in Development, PHP and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply