PHP implode_with_key(); Implode array with key and value

function implode_with_key($assoc, $inglue = '>', $outglue = ',') {
    $return = '';

    foreach ($assoc as $tk => $tv) {
        $return .= $outglue . $tk . $inglue . $tv;
    }

    return substr($return, strlen($outglue));
}

See also http_build_query().

8 comments

  1. anonymous

    This is great!!!!! expecially if you need to store serialized multidimensional array into database!

    thank's!

  2. anonymous

    why there is $return = ''; as very first line of the function ..... this code will never give yu the result....but still i Appriciate your work helped me a lot thanx

  3. anonymous

    for storing into database look at serialize(), base64encode()

  4. anonymous

    this code will give a result; "$return" is not the same as "return"

  5. anonymous
    What about: function implode_with_key($assoc, $inglue = ':') {     if(is_array($assoc) && count($assoc)>0)     {         foreach ($assoc as $tk => $tv)         {             $return[] = $tk . $inglue . $tv;         }         return implode(';', $return);     }     return false; }
  6. anonymous

    This is exactly what I was looking for! Thanks for sharing.

  7. anonymous

    This is exactly what I was looking for! Thanks for sharing.

    I changed the inglue from , to =>. Makes more sense to me.

  8. anonymous
    function explode_with_key($assoc, $indelimiter = '=', $outdelimiter = '|') {     $return = [];     $assoc = explode($outdelimiter, $assoc);     foreach ($assoc as $ts) {         list($key, $value) = explode($indelimiter, $ts);         $return[$key] = $value;     }     return $return; }

Leave a Reply