PHP: Simple Method to Implode or Explode Arrays with Keys CodeUnit 21 NOV 2011

Associative arrays are very useful beasts, because values tied to keys makes it so much easier to build up pseudo objects in that it makes it easier to see which piece of array data refers to what.

There are a number of ways to store associative arrays of course, but this particular one below is probably one of the simplest for getting a single string out of a one level array with keys, and then transforming back into its array form when you need to make use of it again.

function array_implode_with_keys($array){
    $return = '';
    if (count($array) > 0){
    foreach ($array as $key=>$value){
    $return .= $key . '||||' . $value . '----';
    }
    $return = substr($return,0,strlen($return) - 4);
    }
    return $return;
}

function array_explode_with_keys($string){
    $return = array();
    $pieces = explode('----',$string);
    foreach($pieces as $piece){
        $keyval = explode('||||',$piece);
        if (count($keyval) > 1){
        $return[$keyval[0]] = $keyval[1];
        } else {
        $return[$keyval[0]] = '';
        }
    }
    return $return;
}

If you look at the code above, you will see that we are making use of delimiters here to keep firstly the keys aparts, and secondly the key from its associated value. In this case we are using —- to split the array elements, and |||| to split the key from its value.

In other words the resulting string is from the implode function is key1||||value1—-key2||||value2—-key3||||value3.

Obviously the explode function just works in reverse.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.