7

I have an array that looks like this:

array('first' => 'value1', 'second' => 'value2', ...);

How can I get all the keys and put them in a comma separated string?

At the very end I need something like this, to do a query:

values IN ('first','second',...)

Thanks

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

5 Answers5

17

should be enough:

echo "'".implode("','", array_keys($array))."'";
Rufinus
  • 29,200
  • 6
  • 68
  • 84
2

array_keys will grab all the keys, implode will combine them into a string.

implode("','", array_keys($array));
newtron
  • 5,938
  • 1
  • 23
  • 19
2

The simple answer is to use array_keys() to get the array indices.

However, since you're using this in SQL, it's important to also properly escape the values:

$db = new PDO( ... );
$sql .= "value IN (" . 
        join(', ', array_map(array($db, 'quote'), array_keys($arr))) . ")";

Or, when you prefer using prepared statements:

$stmt = $db->prepare('... WHERE value IN (' . 
    join(',', array_fill(0, count($arr), '?')) . ')');
$stmt->execute(array_keys($arr));
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0
$result = '';
$keys = array_keys($array);

foreach($keys as $key) { 
$result .= $key.',';
}

$result = rtrim($result, ',');
Rami
  • 381
  • 2
  • 4
  • 15
-1

Have a at array_keys. It seems like the thing you need. To combine the keys, use implode as suggested by many other users:

implode("','", array_keys($array));
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176