Skip to content

Instantly share code, notes, and snippets.

@simonhamp
Last active February 6, 2023 03:19
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonhamp/a389ee4286e0a4aab6cdddb0d5f7a6d8 to your computer and use it in GitHub Desktop.
Save simonhamp/a389ee4286e0a4aab6cdddb0d5f7a6d8 to your computer and use it in GitHub Desktop.
Laravel: Str::csvToArray macro
<?php
namespace App\Providers;
use Illuminate\Support\Str;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
/**
* Turn a CSV string into a clean array.
*
* @param string $string
* @return array
*/
Str::macro('csvToArray', function ($string) {
return array_filter(array_map('trim', str_getcsv($string)));
});
}
}
@simonhamp
Copy link
Author

simonhamp commented Feb 15, 2018

Here's a simple function to quickly turn a CSV string into an array. It will trim the values and filter any empty ones so you always end up with a pretty clean array without too much fuss, for example:

$string = "some, crazy, , , , mixed, bag, of , comma-separated values, , ,";

$array = Str::csvToArray($string);

// $array => ['some', 'crazy', 'mixed', 'bag', 'of', 'comma-separated values']

Ideal for occasional strings of values that are most easily separated by commas, such as .env/config/query string parameters. May not be so useful on large CSV files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment