Community warning: If that string comes from a csv file, use of
str_getcsv()instead is strictly advised, as suggested in this answer
Try explode:
$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);
Output :
Array
(
[0] => 9
[1] => admin@example.com
[2] => 8
)
Answer from Matthew Groves on Stack OverflowCommunity warning: If that string comes from a csv file, use of
str_getcsv()instead is strictly advised, as suggested in this answer
Try explode:
$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);
Output :
Array
(
[0] => 9
[1] => admin@example.com
[2] => 8
)
$string = '9,admin@google.com,8';
$array = explode(',', $string);
For more complicated situations, you may need to use preg_split.
how to convert comma separated string to array in array - PHP Coding Help - PHP Freaks
How to convert items in array to a comma separated string in PHP? - Stack Overflow
Convert php array into a comma separated list of strings - Stack Overflow
php - Convert array of comma-separated strings to a flat array of individual values - Stack Overflow
Use implode:
$tags = implode(', ', array('tag1','tag2','tag3','tag4'));
Yes you can do this by using implode
$string = implode(', ', $tags);
And just so you know, there is an alias of implode, called join
$string = join(', ', $tags);
I tend to use join more than implode as it has a better name (a more self-explanatory name :D )
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();
You can do this in Laravel 5.8 as follows:
DB::table('users')->select('username')->pluck('username')->unique()->flatten();
Hope this helps.
$data = preg_split('/,\s*/', implode(',', $data));
You can use the following solution:
$result = array();
foreach($inputArray as $value) {
$result = array_merge($result, explode(',', $value));
}
Demo!
Original answer:
$arr = array('1,24,5', 4, '88, 12, 19, 6');
$result = array();
foreach ($arr as $value) {
if(strpos($value, ',') !== FALSE) {
$result = array_merge($result, explode(',', $value));
$result = array_map('trim', $result); // trim whitespace
}
else {
$result[] = trim($value);
}
}
print_r($result);