Search code examples
phparrayscsvexplode

PHP explode comma separated string into array


Lets say I have a text field with the following data. Lines starting with # are comments. The first line is the column headers and values are comma separated.

# some instruction
# some instruction
Day,Open,Close
Monday,09:00,17:00
Tuesday,09:00,18:00

How can I explode this to get an array like this:

$openingTimes = [
   ['Day' => 'Monday', 'Open' => '09:00', 'Close' => '17:00'],
   ['Day' => 'Tuesday', 'Open' => '09:00', 'Close' => '18:00'],
];

Solution

  • If you first split the text field by a new line, then process each line one at a time.

    Ignore anything starting with a # (the $line[0] == '#' bit).

    Use str_getcsv() to split the line into separate fields (allowing for quoted fields etc.) Then if there hasn't been a header so far, then store this split value as the header. If there has been a header, then add this new data as part of the output, combining it with array_combine()...

    $input = '# some instruction
    # some instruction
    Day,Open,Close
    Monday,09:00,17:00
    Tuesday,09:00,18:00';
    
    $lines = explode(PHP_EOL, $input);
    $header = null;
    $output = [];
    foreach ( $lines as $line ) {
        if ( $line[0] == '#' )  {
            continue;
        }
        $data = str_getcsv($line);
        if ( $header == null )  {
            $header = $data;
        }
        else    {
            $output[] = array_combine($header, $data);
        }
    }
    
    print_r($output);