Reputation: 19
I am trying to PAD zeros to the left in order to display in a CSV. But it does not work. I tried STR_PAD_RIGHT (for testing Purpose) which works.
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
if (ctype_digit(($row["$i"]))) {
$num = intval($row["$i"]);
$num1 = str_pad($num, 4, '0', STR_PAD_LEFT);
$out_csv .= '"' . $num1 . '",';
} else {
$out_csv .= '"' . $row["$i"] . '",';
}
}
$out_csv .= "\n";
}
Upvotes: 0
Views: 8431
Reputation: 426
If you open the resulting CSV with a spreadsheet (excel, libreOffice...), it will delete the zeros. Check with a simple notepad if the zeros are there or not. If yes, it's the spreadsheet, if you want to display them, you have to put another character first (like a dot for example). If no, your values are they up to 4 chars ? because str_pad only fill up to the 2nd parameter (here, 4). So if your value is 1234, it won't fill with zeros. If your value is 123, it should display 0123.
Upvotes: 2
Reputation: 401
Ideone snippet STR_PAD_LEFT snippet shows that it works fine.
$num = 1;
$num1 = ''.str_pad($num, 4, '0', STR_PAD_LEFT);
echo $num1;
Upvotes: 0