Jul 3 / Richard Knop

Implode an associative array

PHP’s implode() function is commonly used to convert an array to a string. But what if you want to implode an associative array and you want both keys and values to be included in the string? For instance:

  1. // here's a fancy associative array
  2. $arr = array('fruit' => 'apple',
  3.              'vegetable' => 'potato',
  4.              'pastry' => 'bread',
  5.              'liquid' => 'milk');
  6.  
  7. // and we want to implode it like this
  8. $imploded = 'fruit: apple, vegetable: potato, pastry: bread, liquid: milk';

I wrote a simple Zend action helper for that purpose:

  1. class My_Controller_Action_Helper_ImplodeAssociativeArray extends Zend_Controller_Action_Helper_Abstract
  2. {
  3.     public function direct($array, $separator = ': ', $glue = ', ')
  4.     {
  5.         // separate the associative array into keys and values
  6.         $keys = array_keys($array);
  7.         $values = array_values($array);
  8.  
  9.         // build a new array with joined kesy and values
  10.         $newArray = null;
  11.         for ($i = 0; $i < count($keys); $i++) {
  12.             $newArray[] = $key . $separator . $value;
  13.         }
  14.  
  15.         // implode and return the new array
  16.         return implode($glue, $newArray);
  17.     }
  18. }

To verify that it works:

  1. echo ($this->_helper->implodeAssociativeArray($arr) == $imploded) ? : 'yes' : 'no';

One Comment

leave a comment
  1. iki / Jun 21 2010

    you should use “foreach ($keys as $key => $value)”

Leave a Comment