How to Convert an Associative Array to String PHP


When working with associate arrays in PHP it may be helpful to convert the array into a string. You can use string functions so that you can display its contents on your Web page. An associate array is an ordered map of key and value pairs, such as "'position' => 'manager', 'name' = 'bob', age = 33." You can convert the associative array into a numerically indexed array and then use the "implode" function to convert it into a string.

  • Open your PHP file in a text editor such as Windows Notepad.

  • Declare an associate array and assign it values by adding the following code in the body of your HTML:

    $my_array = array("key1" => "value1", "key2" => "value2", "key3" => "value3");

  • Call the "array_map" function to change the associate array into an indexed array that the "implode" function will work on by adding the code:

    function merge_arrays ($key, $value)


    return $key .":". $value .", ";


    $fixed_array = array_map("merge_arrays", array_keys($my_array), array_values($my_array));

    The "array_map" function will call the "merge_arrays" function for every key and value pair in the array, mapping the results into another array. The "array_keys" function provides each key of the array and "array_values" provides the values of the array. Using the example, "fixed_array" will have a value of:

    0 => key1: value1,

    1 => key2: value2,

    2 => key3: value3,

  • Convert the array to a string with the "implode" function and print the value by adding the code:

    print implode($fixed_array);

    Using the example, this will output

    key1: value1, key2: value2, key3: value3,

  • Save the PHP file and load it on your web server to convert the associate array into an array.

Related Searches


Promoted By Zergnet


Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!