Categories
PHP

Convert a delimited string into an array

How to parse a CSV, tab, space, or any other single-byte character delimited string into an array using the str_getcsv() function.

<?php
 //Syntax
 str_getcsv(
  string $string, string $separator = ",",
  string $enclosure = "\"",string $escape = "\\"
 ): array

This function takes four parameters:

  1. $string: the string to parse
  2. $separator (optional): the delimiter (one single-byte character only), default delimiter is , (comma).
  3. $enclosure (optional): one character (single-byte), default enclosure character is ", by default double-qutations marks will be deleted if a value surrounded by them. See example.
  4. $escape (optional): the escape character (single-byte), default is backslash \, use an empty string "" to disable this parameter.

The str_getcsv() function reads data from a string and converted into an array. By default it parsed the comma separated values, see examples:

Example: Parses comma-delimited string into an array.

<?php
 $csvStr = '"a","b","c","d"'; 
 $array = str_getcsv($csvStr);
 print_r($array);
 //Array ( [0] => a [1] => b [2] => c [3] => d )

Example: Parse tab-separated string into an array

<?php
#Tab separated values enclosed in pipe sign
 $csvStr = '|a|	|b|	|c|	|d|'; 
#Set tab as separator, use keyboard tab key or \t 
 $array = str_getcsv($csvStr,"\t");
 print_r($array);
 /*Array
(
    [0] => |a|
    [1] => |b|
    [2] => |c|
    [3] => |d|
)*/

#Set separator and enclosure values
 $array = str_getcsv($csvStr,"\t", '|');
 print_r($array);
 /*Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)*/

Example: Parses comma separated multi-line string into an array.

The ollowing example demonstrates, how to parse multiple lines of CSV data using str_getcsv() function. First, we parsed the string, we used newline \n as a separator and received lines (rows) and then parsed each line with the str_getcsv() function to split the lines into individual cell values (array):

<?php
 $csvMultirows = 'h1,h2,h3,h4
a1,b1,c1,d1
a2,b2,c2,d2
a3,b3,c3,d3';

 $rows = str_getcsv($csvMultirows, "\n");
 echo '<pre>';
 foreach ($rows as $row){
  $cells = str_getcsv($row);
  foreach ($cells as $cell)
   echo $cell.' ';
  echo "\n";
 }
/* Prints: 
h1 h2 h3 h4 
a1 b1 c1 d1 
a2 b2 c2 d2 
a3 b3 c3 d3*/

Working with arrays:

  1. Creating Arrays
  2. Array Iteration
  3. Array Internal Pointers
  4. Explode and Implode Functions
  5. Count Array Elements, Find Min and Max Values
  6. Search values and keys in arrays
  7. Filter array elements using array_filter()
  8. Modify array elements using array_map() and array_walk()
  9. Split, tokenize, and iterate a string
  10. Convert a delimited string into an array
  11. Sorting arrays