I need a one liner to get from this [1, 2, 3] to ["1", "2", "3"]

I am grabbing ids from users:
DB::table('users')
->get()
->pluck('id')
DB::table('users')
->get()
->pluck('id')
and this will give me an array with integers like:
[1, 2, 3, 4, ...]
[1, 2, 3, 4, ...]
However, I need to make it like this:
["1", "2", "3", "4", ...]
["1", "2", "3", "4", ...]
so basically strings in an array, or perhaps json like format, right? The questions is how to do that without a closure or multiple variables or foreach loop etc. Basically I need a one liner to be able to stick it in default() or other form field related parts, etc. I have tried
json_encode(
DB::table('users')
->get()
->pluck('id')
)
json_encode(
DB::table('users')
->get()
->pluck('id')
)
But the result is:
"[1, 2, 3, 4]"
"[1, 2, 3, 4]"
So, it encapsulate the whole array as a string instead of its elements. Any idea how to elegantly solve this problem? Can I perhaps cast somehow the pluck('id') into string during the get process? Or is there some trick how to do this easy?
7 Replies
awcodes
awcodes9mo ago
collect($array)->each(fn($item) => (string) $item)->toArray()
collect($array)->each(fn($item) => (string) $item)->toArray()
Not sure why it has to be a one liner though. 😀 Also don’t encode it.
Wirkhof
WirkhofOP9mo ago
Thanks but:
collect(
DB::table('users')
->get()
->pluck('id')
)->each(fn ($item) => (string) $item)->toArray()
collect(
DB::table('users')
->get()
->pluck('id')
)->each(fn ($item) => (string) $item)->toArray()
still gives me an array of integers and not an array of strings. I have tried both dd() and to save it in the database and the result is still:
[1, 2, 3, 4, ...]
[1, 2, 3, 4, ...]
instead of
["1", "2", "3", "4", ...]
["1", "2", "3", "4", ...]
For example, I have noticed that the checkbox list method saves selected chckboxes, it's saved nicely as ["1","2","3",...] . How it is doing that?
awcodes
awcodes9mo ago
What are you trying to do, I would expect the checkbox list to handle it all when providing those as the options.
Wirkhof
WirkhofOP9mo ago
I will probably try raw regex and put strings around each element. Which PHP regex function would be the best for this job?
awcodes
awcodes9mo ago
I think you’re probably over complicating this. That’s why I asked what your were actually trying to accomplish.
Wirkhof
WirkhofOP9mo ago
In 1 column in the DB I have [1, 2, 3, 4, ...] and in other I have this ["1", "2", "3", "4", ...] and in other [1, 2, 3, 4, ...] so I always have to convert stuff. That's why I want strings and not integers for everything.
awcodes
awcodes9mo ago
Hmm. To me that points to a bigger underlying issue with your data structure / column casts.
Want results from more Discord servers?
Add your server