Skip to main content
edited title
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481

Creating comma-separated '?' placeholders for SQL query pars eterstparameters

edited title
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481

Better alternative in for loop for creating Creating comma-separated list'?' placeholders for SQL query pars eterst

Source Link
sam
  • 243
  • 1
  • 10

Better alternative in for loop for creating comma-separated list

I have come up with a code that takes the total number of an array and creates ? for each, then separates them by a comma; leaving me a list like the one below:

?, ?, ?, ?, ?...

I am using this for my sql queries with prepared statements, instead of having to create the prepared statement each time, I want to just have an easily accessible class that does the heavy work.

So far I have a for loop code which I came up with to get the comma-separated question marks. First I create an array of [0] => ? ... based on the total number of the original array and then implode the value and add the comma between each element.

<?php
$arr = array(
    'name' => 'James Bond',
    'age' => 60,
    'hobbies' => 'Saving England',
    'country' => 'England',
    'language' => 'English',
    'children' => 'too many to count'
);

for($i = 0; $i < count($arr); $i++)
{
    $question[$i] = '?';
}    
print_r( implode(', ', $question) );
// outputs: ?, ?, ?, ?, ?, ?
?>

Now my question is, is there a more efficient way of achieving this, such as a one-liner that just takes the total array number and creates the number automatically?