0

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);
        }
3

7 Answers 7

3
$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.

Sign up to request clarification or add additional context in comments.

Comments

2
$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);

Comments

1

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

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

See : array_keys

Comments

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

Comments

0

Use php array_keys and implode methods

print implode(PHP_EOL, array_keys($element))

Comments

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

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

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.