PHPverse 2025

Voting

: min(seven, six)?
(Example: nine)

The Note You're Voting On

kamil dot dratwa at gmail dot com
3 years ago
This part of the length parameter behavior description is tricky, because it's not mentioning that separator is considered as a char and converted into an empty string: "Otherwise the line is split in chunks of length characters (...)".

First, take a look at the example of reading a line which does't contain separators:

<?php
file_put_contents
('data.csv', 'foo'); // no separator
$handle = fopen('data.csv', 'c+');
$data = fgetcsv($handle, 2);
var_dump($data);
?>

Example above will output:
array(1) {
[0]=>
string(2) "fo"
}

Now let's add separators:

<?php
file_put_contents
('data.csv', 'f,o,o'); // commas used as a separators
$handle = fopen('data.csv', 'c+');
$data = fgetcsv($handle, 2);
var_dump($data);
?>

Second example will output:

array(2) {
[0]=>
string(1) "f"
[1]=>
string(0) ""
}

Now let's alter the length:

<?php
file_put_contents
('data.csv', 'f,o,o');
$handle = fopen('data.csv', 'c+');
$data = fgetcsv($handle, 3); // notice updated length
var_dump($data);
?>

Output of the last example is:

array(2) {
[0]=>
string(1) "f"
[1]=>
string(1) "o"
}

The final conclusion is that while splitting line in chunks, separator is considered as a char during the read but then it's being converted into empty string. What's more, if separator is at the very first or last position of a chunk it will be included in the result array, but if it's somewhere between other chars, then it will be just ignored.

<< Back to user notes page

To Top