Put all indexs of array in a comma separated string [closed]
Asked Answered
T

5

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

Tapioca answered 17/1, 2013 at 13:42 Comment(5)
array_keys() would do that for you.Octopus
@Jack not quite. That will give them an array of the keys. They will then have to implode() that.Feldstein
Have a look at this question. It deals with a similar problem.Cuevas
@PatrickJamesMcDougle op already has implode tag on the question, so my comment should give enough information.Octopus
BTW, instead of injecting that string directly, you really should make sure that you are using PDO prepared statements for this. php.net/manual/en/pdo.prepared-statements.phpFeldstein
C
17

should be enough:

echo "'".implode("','", array_keys($array))."'";
Canter answered 17/1, 2013 at 13:44 Comment(3)
Comment deleted because I was being dumb.Feldstein
nope, explode = string to array; implode = array to stringCanter
@PatrickJamesMcDougle hapens to the best of us :DCanter
C
2

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

implode("','", array_keys($array));
Clincher answered 17/1, 2013 at 13:45 Comment(0)
C
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));
Colloidal answered 17/1, 2013 at 13:51 Comment(2)
IMHO it would be much better to use VALUE IN (?) and ->execute(array(implode("','",array_keys($array))Canter
@Canter I wouldn't say much better, but that's a good alternative :)Octopus
B
0
$result = '';
$keys = array_keys($array);

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

$result = rtrim($result, ',');
Been answered 17/1, 2013 at 13:46 Comment(1)
this will lead to first, second not to 'first','second'Canter
W
-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));
Welfarism answered 17/1, 2013 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.