str_getcsv()

str_getcsv() — Parse a CSV string into an array.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5 >= 5.3.0, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

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

Signature

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

Parameters

ParameterTypeWhat it takes
$stringstringThe string to parse.
$separatorstringThe separator parameter sets the field separator. It must be a single byte character.
$enclosurestringThe enclosure parameter sets the field enclosure character. It must be a single byte character.
$escapestringThe escape parameter sets the escape character. It must be a single byte character or the empty string. The empty string ("") disables the proprietary escape mechanism.

Return value

Returns an indexed array containing the fields read.

Example

A runnable snippet:

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

Output:

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

Changelog

VersionChange
8.4.0Relying on the default value of escape is now deprecated.
8.4.0Now throws a ValueError if separator, enclosure, or escape is invalid. This mimics the behavior of fgetcsv() and fputcsv().
8.3.0An empty string is returned instead of a string with a single null byte for the last field if it contains only an unterminated enclosure.
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.

See also

fputcsv(), fgetcsv()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page str_getcsv() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.