Last active
February 6, 2023 03:19
-
-
Save simonhamp/a389ee4286e0a4aab6cdddb0d5f7a6d8 to your computer and use it in GitHub Desktop.
Laravel: Str::csvToArray macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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))); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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.