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:
-
// here's a fancy associative array
-
$arr = array('fruit' => 'apple',
-
'vegetable' => 'potato',
-
'pastry' => 'bread',
-
'liquid' => 'milk');
-
-
// and we want to implode it like this
-
$imploded = 'fruit: apple, vegetable: potato, pastry: bread, liquid: milk';
I wrote a simple Zend action helper for that purpose:
-
class My_Controller_Action_Helper_ImplodeAssociativeArray extends Zend_Controller_Action_Helper_Abstract
-
{
-
public function direct($array, $separator = ': ', $glue = ', ')
-
{
-
// separate the associative array into keys and values
-
$keys = array_keys($array);
-
$values = array_values($array);
-
-
// build a new array with joined kesy and values
-
$newArray = null;
-
for ($i = 0; $i < count($keys); $i++) {
-
$newArray[] = $key . $separator . $value;
-
}
-
-
// implode and return the new array
-
return implode($glue, $newArray);
-
}
-
}
To verify that it works:
-
echo ($this->_helper->implodeAssociativeArray($arr) == $imploded) ? : 'yes' : 'no';
