1

I have the following array:

$arr = [
    0 => 'value1',
    1 => 'value2',
    2 => 'value3'
];

The select function of my db class takes arguments in the following format:

DB::table('users')->select('value1', 'value2', 'value3')

How can I convert my array to pass those values in my select function?

I tried implode(',', $arr) and it gives one string with comma separated values, but what I want is not a single string, it's a list of comma separated strings like in the example above.

Thanks for any help.

2
  • 1
    Perhaps DB::table('users')->select(...$arr) if you're using a modern version of PHP; or simply DB::table('users')->select($arr), as the select method will accept an array of arguments Commented Aug 29, 2016 at 14:31
  • one solution: DB::table('users')->select("'".implode("','",$array)."'") Commented Aug 29, 2016 at 14:35

2 Answers 2

3

select() can accept an array, so try:

DB::table('users')->select($arr);

This is source code of select() method:

public function select($select = null)
{
    ....

    // In this line Laravel checks if $select is an array. If not, it creates an array from arguments.
    $selects = is_array($select) ? $select : func_get_args();
Sign up to request clarification or add additional context in comments.

1 Comment

It actually "prefers" an array, great!
0

You can do this in Laravel 5.8 as follows:

DB::table('users')->select('username')->pluck('username')->unique()->flatten();

Hope this helps.

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.