Technology Software

How to Convert an Associative Array to String PHP

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

    • 2). 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");

    • 3). 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,

    • 4). 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,

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

Leave a reply