Skip to content
Advertisement

Keep leading zeros with fgetcsv in PHP

I’m reading a .csv file (I have no control of the format of the file) and I’m trying to keep the leading zeros for the data in the resulting array. For instance, the .csv file has “0615” in a field, but resulting array contains “615”. There are also fields in the .csv file that do not contain leading zeros, so adding zeros to the beginning of each field will not work.

I’ve tried to force functions to read the fields as a string, but explode, str_getcsv, fgetcsv all parse it as an integer and remove the leading zero beforehand. Any thoughts?

Edit: explode does NOT remove the leading zeros. Using explode with fgets works.

Advertisement

Answer

explode() works on a string basis; your type conversion must be happening elsewhere:

$data = "00555,00666,00777,00888";
$a = explode(",",$data);
foreach($a as $b) echo $b . " ";         // 00555 00666 00777 00888

Use (string)$b if PHP insists on interpreting the strings as integers.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement