Implode array of values as well as its keys
Asked Answered
C

3

11

I'm trying to implode an array of both its keys and values. I can easily get the keys with the implode, but find I have to repeat myself for the keys.

Currently I am doing this:

$values = array(
  'id'                    =>  $sel['id'],
  'creator_id'            =>  $sel['creator_id'],
  'campaign_id'           =>  $sel['campaign_id'],
  'save_results'          =>  $sel['save_results'],
  'send_results_url'      =>  $sel['send_results_url'],
  'reply_txt'             =>  $sel['reply_txt'],
  'allow_multiple_votes'  =>  $sel['allow_multiple_votes']
    );
    $cols = '';
    $vals = '';
    $first = true;
    foreach($values as $col => $val) {
        if(!$first) {
            $cols .= ', ';
            $vals .= ', ';
        }
        $cols .= $col;
        $vals .= $val;
        $first = false;
    }

The part that bothers me is this:

foreach($values as $col => $val) {
  if(!$first) {
    $cols .= ', ';
    $vals .= ', ';
  }
  $cols .= $col;
  $vals .= $val;
  $first = false;
}

Is there a way to implode the array keys?

For example, I could do

$vals = implode(', ', $values);

to implode the values, but I need to do this as well for the keys.

I could also use

$keys = array();
    foreach($values as $col => $val)
        $keys[] = $col;
    $cols = implode(', ', $keys);
    $rows = implode(', ', $values);

but it still requires me to loop over it creating another array, surely there is a better way, do just get the keys?

Carnation answered 13/7, 2010 at 2:59 Comment(0)
E
67
$cols = implode(', ',array_keys($values));
Estellestella answered 13/7, 2010 at 3:0 Comment(0)
M
2

This function will extract keys from a multidimensional array

<?php 
function multiarray_keys($ar) { 

    foreach($ar as $k => $v) { 
        $keys[] = $k; 
        if (is_array($ar[$k])) 
            $keys = array_merge($keys, multiarray_keys($ar[$k])); 
    } 
    return $keys; 
} 
?> 
Mor answered 23/7, 2012 at 8:44 Comment(0)
D
0

print_r($values,true);

Then removing the first two lines and the last line from the result:

Array
(
    [foo] => bar
    [baz] => boom
)
Detwiler answered 10/10, 2012 at 18:59 Comment(1)
@James Actually, this returns a string and doesn't dump anything as output. Take a look at the manual. This is a very viable solution if all you need to do is get keys and values from an array into a single string.Penelopa

© 2022 - 2024 — McMap. All rights reserved.