note 126638 added to function.fgetcsv

From: Date: Wed, 24 Nov 2021 21:49:27 +0000
Subject: note 126638 added to function.fgetcsv
Groups: php.notes 
Request: Send a blank email to php-notes+get-217294@lists.php.net to get a copy of this message
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. ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.85.242 (proxied: 2a01:111f:b78:2f00:d97d:99df:604d:10ca) ---- Manual Page -- https://php.net/manual/en/function.fgetcsv.php Edit -- https://main.php.net/note/edit/126638 Del: integrated -- https://main.php.net/note/delete/126638/integrated Del: useless -- https://main.php.net/note/delete/126638/useless Del: bad code -- https://main.php.net/note/delete/126638/bad+code Del: spam -- https://main.php.net/note/delete/126638/spam Del: non-english -- https://main.php.net/note/delete/126638/non-english Del: in docs -- https://main.php.net/note/delete/126638/in+docs Del: other reasons-- https://main.php.net/note/delete/126638 Reject -- https://main.php.net/note/reject/126638 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#217294) next »