Ryan
Ryan

Reputation: 14659

How to create a string that contains the keys of a given array in PHP?

I have an array holding this data:

Array ( 
  [1402377] => 7 
  [1562441] => 7 
  [1639491] => 9 
  [1256074] => 10 
 )

How can create a string that contains the keys of the above array? Essentially, I need to create a comma separated string that consists of an array's keys

The string would look like: 'key','key','key'

Do I need to create a new array consisting of the keys from an existing array?

The reason I need to do this is because I will be querying a MySQL database using a WHERE in () statement. I would rather not have to query the database using a foreach statement. Am I approaching this problem correctly?

I've tried using a while statement, and I'm able to print the array keys that I need, but I need those keys to be an array in order to send to my model.

The code that allowed me to print the array keys looks like this:

while($element = current($array)) {
            $x = key($array)."\n";
            echo $x;
            next($array);
        }

Upvotes: 0

Views: 153

Answers (7)

outis
outis

Reputation: 77450

Imploding the arguments and interpolating the result into the query can cause an injection vulnerability. Instead, create a prepared statement by repeating a string of parameter placeholders.

$paramList = '(' . str_repeat('?, ', count($array) - 1) . '?)'
$args = array_keys($array);
$statement = 'SELECT ... WHERE column IN ' . $paramList;
$query = $db->prepare($statement);
$query->execute($args);

Upvotes: 0

OptimusCrime
OptimusCrime

Reputation: 14863

The string would look like: 'key','key','key'

$string = '\'' . implode('\',\'', array_keys($array)) . '\'';

Upvotes: 0

WoLfulus
WoLfulus

Reputation: 1977

implode(', ', array_keys($array));

Upvotes: 1

Nazariy
Nazariy

Reputation: 6088

Use php array_keys and implode methods

print implode(PHP_EOL, array_keys($element))

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205


$yourString = '';
foreach($yourArr as $key => $val) {
 $yourString .=$key.",";
}
echo rtrim($yourString, ",");

//OR
$yourString = implode(",", array_keys($yourArray));

See : array_keys

Upvotes: 1

hoppa
hoppa

Reputation: 3041

$string = implode(',', array_keys($array));

By the way, for looping over an array consider not using current and next but use foreach:

foreach ($array as $key => $value) {
    //do something
}

This will automatically iterate over the array until all records have been visited (or not at all if there are no records.

Upvotes: 3

Cyclonecode
Cyclonecode

Reputation: 30131

$keys = array_keys($array);
$string = implode(' ',$keys);

In your case, were you are using the result in a IN clause you should do: $string = implode(',', $keys);

Upvotes: 2

Related Questions