php8.5
Home/ Manual/ strings / functions/ str_getcsv

str_getcsv

PHP function Edit on GitHub ✎

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Parse a CSV string into an array

Description

str_getcsv(string $string, string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array

Parses a string input for fields in CSV format and returns an array containing the fields read.

Parameters

string

The string to parse.

Escape-parameter

Return Values

Returns an indexed array containing the fields read.

Changelog

VersionDescription
8.4.0Now throws a ValueError if separator, enclosure, or escape is invalid. This mimics the behavior of fgetcsv() and fputcsv().
7.4.0The escape parameter now interprets an empty string as signal to disable the proprietary escape mechanism. Formerly, an empty string was treated like the default parameter value.

Examples

str_getcsv() example

php
<?php

$string = 'PHP,Java,Python,Kotlin,Swift';
$data = str_getcsv($string, escape: '\\');

var_dump($data);
?>

The above example will output:

output
array(5) {
  [0]=>
  string(3) "PHP"
  [1]=>
  string(4) "Java"
  [2]=>
  string(6) "Python"
  [3]=>
  string(6) "Kotlin"
  [4]=>
  string(5) "Swift"
}

str_getcsv() example with an empty string

Caution

On an empty string this function returns the value [null] instead of an empty array.

php
<?php

$string = '';
$data = str_getcsv($string, escape: '\\');

var_dump($data);
?>

The above example will output:

output
array(1) {
  [0]=>
  NULL
}

See Also

  • fputcsv()
  • fgetcsv()
  • SplFileObject::fgetcsv
  • SplFileObject::fputcsv
  • SplFileObject::setCsvControl
  • SplFileObject::getCsvControl

Source: reference/strings/functions/str-getcsv.xml · from the official PHP manual (php/doc-en)