phparrayskey-valueimplodedelimited

Reduce an associative array to pipe-delimited sets of hyphen-separated key-value pairs


I have this array:

array (size=5)
  35 => string '3' (length=1)
  24 => string '6' (length=1)
  72 => string '1' (length=1)
  16 => string '5' (length=1)
  81 => string '2' (length=1)

I want to implode sets of key-value pairs to get:

$str = '35-3|24-6|72-1|16-5|81-2';

How to get it the easy way?


Solution

  • I haven't tested this, but it should be pretty straight forward ...

    foreach($array as $key=>$item){
        $new_arr[] = $key."-".$item;
    }
    
    $str = implode('|', $new_arr);