implode_assoc

I was fiddling around on a project and created this associative array implosion function that incorporates several of the ideas from the php.net documentation's entry on implode, but which also adds a whack of nifty options. Documentation and examples are included in-line.

NOTE: This is function is a bit heavy; one would obviously want to create a slimmer example for any time-sensitive operations.

<?php
/**
 * Implodes a single dimensional associative array with various formatting options / modifiers.
 *
 * @param array $array single dimensional array to implode
 * @param array $overrideOptions is an key->value array with the following valid values:
 * - inner_glue           =>  string to connect keys to values with
 * - outer_glue           =>  string to connect keys-value pairs together
 * - prepend              =>  string to attach to the front of the final result
 * - append               =>  string to attach to the end of the final result
 * - skip_empty           =>  bool if true then do not include entries with values that evaluate to false
 * - prepend_inner_glue   =>  bool if true then stick the inner_glue on to the front of all key-value pairs
 * - append_inner_glue    =>  bool if true then stick the inner_glue on to the end of all key-value pairs
 * - prepend_outer_glue   =>  bool if true then stick the outer_glue on to the front of the return string
 * - append_outer_glue    =>  bool if true then stick the outer_glue on to the end of the return string
 * - urlencode            =>  bool if true then urlencode() all returned values
 * - part                 =>  string setting what part(s) of the key-value pairs to return; valid values:
 *   - both   ->  display both the key and the value
 *   - key    ->  display the key and NOT the value; inner_glue will not display except with prepend/append
 *   - value  ->  display the value and NOT the key; inner_glue will not display except with prepend/append
 *
 * @author Sean P. O. MacCath-Moran -- http://emanaton.com/code/php/implode_assoc
 *
 * @example
 *  $titleParts = array('Type'=>'Image', 'Size'=>'16 Meg', 'Description'=>'', 
 *                      'Author'=>'Sean P. O. MacCath-Moran', 'Site'=>'www.emanaton.com');
 *  echo implode_assoc($titleParts, array('inner_glue'=>': ', 'outer_glue'=>' || ', 
 *                                        'skip_empty'=>true));
 *      Type: Image || Size: 16 Meg || Arther: Sean P. O. MacCath-Moran || Site: www.emanaton.com
 *
 * $htmlArgs = array('href'=>'http://www.emanaton.com/', 'title'=>'emanaton dot com', 'style'=>'',
 *                   'class'=>'promote siteLink');
 * echo implode_assoc($htmlArgs, array('inner_glue'=>'="', 'outer_glue'=>'" ', 'skip_empty'=>true,
 *  'append_outer_glue'=>true, 'prepend'=>'<a ', 'append'=>'>'));
 *     <a href="http://www.emanaton.com/" title="emanaton dot com" class="promote siteLink" >
 *
 * $getArgs = array('page'=>'2', 'id'=>'alpha1', 'module'=>'acl', 'controller'=>'role', 'action'=>'',
 *                  'homepage'=>'http://www.emanaton.com/');
 * echo implode_assoc($getArgs, array('skip_empty'=>true, 'urlencode'=>true));
 *     page=2&id=alpha1&module=acl&controller=role&template=default&value=http%3A%2F%2Fwww.emanaton.com%2F
 *
 * @return string of the imploded key-value pairs
*/
function implode_assoc($array, $overrideOptions = array()) {
  
  // These default options set the defaults but are over-written by matching values from $overrideOptions
  $options = array(
    'inner_glue'=>'=',
    'outer_glue'=>'&',
    'prepend'=>'',
    'append'=>'',
    'skip_empty'=>false,
    'prepend_inner_glue'=>false,
    'append_inner_glue'=>false,
    'prepend_outer_glue'=>false,
    'append_outer_glue'=>false,
    'urlencode'=>false,
    'part'=>'both' //'both', 'key', or 'value'
  );
  
  // Use values from $overrideOptions that match keys in $options and then extract those values into 
  // the current workspace.
  foreach ($overrideOptions as $key=>$val) { if (isset($options[$key])) {$options[$key] = $val;} }
  extract($options);
  
  // $output holds the imploded results of the key-value pairs
  $output = array();
  
  // Create a collection of the inner key-value pairs and glue them as indicated by the $options
  foreach($array as $key=>$item) {
    // If not skipping empty values OR if the item evaluates to true. 
    // i.e. If $skip_empty is true then check to see if the array item's value evaluates to true.
    if (!$skip_empty || $item) {
      $output[] =
        ($prepend_inner_glue ? $inner_glue : '').
        ($part != 'value' ? $key : ''). // i.e. show the $key if $part is 'both' or 'key'
        ($part == 'both' ? $inner_glue : '').
        // i.e. show the $item if $part is 'both' or 'value' and optionally urlencode $item
        ($part != 'key' ? ($urlencode ? urlencode($item) : $item) : '').
        ($append_inner_glue ? $inner_glue : '')
      ;
    }
  }
  
  return
    $prepend.
    ($prepend_outer_glue ? $outer_glue : '').
    implode($outer_glue, $output).
    ($append_outer_glue ? $outer_glue : '').
    $append
  ;
}

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Congrats

What a very useful function!!!! I can not count the times I lost too many time constructing queries.
Thanks

Wowwa

Coooooooooool and Nice. Thanks a BILLION !!!

Nice script

Thanks for this script, got me out of a hole quickly since I wanted to store post fields easily for a transaction log in the database. worked a treat. :-)

Thanks

Very useful.
Thanks!

Re: Thanks

I *love* getting notes like this. It makes me feel good about having put in the effort to make this publicly available. So - thanks right back at cha, Guido! (and to everyone else!)

Sean P. O. MacCath-Moran
www.emanaton.com

Thanks for sharing! :)

Just what I needed, found it from your post at PHP: implode. Thanks!

very handy

Good work, saved me time when i was working on something entirely different and needed exactly this function.
ty!

Woot!

I'm glad to hear it!

Sean P. O. MacCath-Moran
www.emanaton.com

great stuff

thanks, it is a bit more than I needet, but thanks to default params it fits perfect.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre>
  • Lines and paragraphs break automatically.
  • Use [fn]...[/fn] (or <fn>...</fn>) to insert automatically numbered footnotes.
  • Web page addresses and e-mail addresses turn into links automatically. (Better URL filter.)
  • Syntax highlight code surrounded by the {syntaxhighlighter SPEC}...{/syntaxhighlighter} tags, where SPEC is a Syntaxhighlighter options string or "class="OPTIONS" title="the title".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.