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.
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.
If you need the leading zeroes for presentation or uniform formatting processes then it might be easier to simply pad the numbers when you output them.
http://php.net/manual/en/function.str-pad.php should be of help here.
Use str_pad to add the leading zeros to the parsed integer, wherever you need it.
Or use sprintf, if you are familiar with it.
$num = 1;
$num = sprintf('%04d', $num);
// ^^
// ||_ How many leading digits?
// |_ Leading digit?
// output: 0001
Related
floatval('19500.00');
returns 19500 ;
however
echo floatval('19,500.00');
returns 19 ;
this could've really given me a big problem it was good that I've noticed :D ... is there some reason for that behavior or it's just a bug ... should all values be number_formatted before ouput?
You put that value in single quotes, so it's not treated as a numerical value, but as a string.
Here's php.net's explanation what happens to strings with floatval (from http://php.net/manual/en/function.floatval.php):
Strings will most likely return 0 although this depends on the
leftmost characters of the string.
Meaning: The leftmost characters of the string in your case is 19 - that's a numerical value again, so the output is 19.
Decimal and thousands separator symbols are defined by current locale used in your script.
You can set default_locale in php.ini globally, or change locale in your script on the go: http://php.net/manual/en/function.setlocale.php
Different locales have different separators. To check, which is the current separator symbol, you can use localeconv function: http://us2.php.net/manual/en/function.localeconv.php
$test = localeconv();
echo $test['decimal_point'];
#.
echo $test['thousands_sep'];
#,
But actually no one can make this function work properly with all these commas and dots, so the only solution is to clean the input removing everything except "." and numbers by regexp or str_replace:
echo floatval(preg_replace("/[^0-9\.]/", "", '19,500.00'));
#19500
echo floatval(str_replace(",", "", '19,500.00'));
#19500
i extract a text from a .txt with file() but the lenght of the words (strlen) is bigger with 2, except the last word;
eg: if my words.txt looks like this :
sql
word
php
strlen(sql) = 5
strlen(word) = 6
strlen(php) = 3
Why? thx
strlen() returns the number of bytes rather than the number of characters in a string.
try using mb_strlen() instead
Probably because of the line ending "\n" at the end of each line. Can you provide the code for reading the file in order to help you better?
To remove all newlines and carriage returns, use this code:
$val = preg_replace('/\r|\n/', '', $val);
I have been handling long numbers in PHP. Like the following examples.
12.020000
12.000000
To get rid of trailing zeros and the decimal point I have been using the following inside a function.
return rtrim(rtrim($str, "0"),".");
So the above turns out like.
12.02
12
It was a bit short sighted as when 1000 gets entered it gets turned into 1.
Can someone please help me with the code to remove trailing zeros after the decimal point only?
Bonus points if the code removes the decimal place but I can always feed it into rtim($str,".").
EDIT: To be clear, I am stripping the decimal place and zeros only when displaying to the screen. Also casting to float is not an option as I also handle numbers like 0.00000001 which come out like 1.0e-9 sort of thing.
Why are you using string to hold numbers? Cast it to float and it'll solve your problem.
$string = '12.020000';
$number = (float) $string; // will be 12.02
Then, if you want to use it as string (but why?)
$string = (string) $number;
The thing that perplexes me about your question is that extra zeros won't be included in a number variable without intentionally adding them with number_format. (This may be why someone down-voted it).
Normally you don't want to use string functions (meant for text) on variables that hold numbers. If you want to round off a number, use a function like round.
http://php.net/manual/en/function.round.php
There's also number_format, which can format numbers by adding zero padding: (it doesn't actuall round, just trims off excess numbers).
http://php.net/manual/en/function.number-format.php
Since your zeros are appearing, it's likely that you simply need to multiple the variable by 1, which will essentially convert a string to a number.
Good luck!
Regarding to fgetcsv() documentation, there are some parameteres inside fgetcsv() function: Handle, length, delimiter, enclosure, and escape.
Now, I have 2 questions:
What does enclosure do exactly?
I have a csv file with 5 columns per line. Imagine it something like this: 1,2,3,4,5
So indexes are from 0 to 4. But whenever I want to get date from index 4, an empty value returns. Unless I put a comma after it (by filling an extra column after it that makes the contents like this: 1,2,3,4,5,6 ). How can I solve this issue ? It seems that there is some problem because of missing comma after the last item in each row of csv file!
1. The enclosure parameter is the character the encapsulates the data for a specific field, or "index". By default, the parameter is a ", which means that you can "enclose" strings in " characters.
Example:
1,2,"this is three",4
2. Per a comment, you're calling fgetcsv($handle, 10000, ','). It's possible, maybe, that the line(s) you're reading are longer than 10000 characters. Try changing the length to 0, which will be "no limit" and see if that helps. Another solution would be to try wrapping the column's value in double-quotes.
Enclosure is the character enclosing the field. It is an extra delimiter, of a sort.
For example hello,world has a comma as field delimiter, and has no text delimiter, while "hello","world" has a quote sign as text delimiter. Some systems employ delimited and undelimited values to indicate text and numeric fields, respectively (I believe Microsoft Excel does). This allows a field to contain the field delimiter in its value:
"Hello,world","Second Field","Third, and last, field".
Some other systems only enclose values containing the field delimiter, or values containing whitespace, which means that on those systems an undelimited value is not necessarily numeric.
If you have a "trivial" case - undelimited values, without escaped field-delimiters inside values (i.e., no 'A,firstpartB\,secondpartB,C' stuff) - you might skip CSV conversion altogether and run
$line = fgets($file, MAX_EXPECTED_LINE_LEN);
// This splits ' A, B, C ' into 'A', ' B' and ' C' (note spaces)
$row = explode(',', trim($line)); // other delimiters can be used
or
// Consider " , ", "," and ", " as the same delimiter
// i.e. ' Alpha , Beta , Gamma ' gets split into 'Alpha', 'Beta' and 'Gamma'
$row = preg_split('#\\s*,\\s*#', trim($line));
I cannot seem to reproduce the problem you are experiencing; could it be related to a different encoding of line endings (i.e., CRLF instead of LF)?
In a pinch, you can divide fgetcsv in the two components fgets and str_getcsv(), manipulating the line between the calls (with trim, or if the worse comes to the worst, by appending the missing comma).
It works to me on this way:
while ($row = $stmt -> fecht()){
echo "\"";
echo $row['email'];
echo "\"";
// Export every row to a file
$arr = array(',');
fputcsv($data, $arr, ";", '"' );
}
Users will be filling a field in with numbers relating to their account. Unfortunately, some users will have zeroes prefixed to the beginning of the number to make up a six digit number (e.g. 000123, 001234) and others won't (e.g. 123, 1234). I want to 'trim' the numbers from users that have been prefixed with zeros in front so if a user enters 000123, it will remove the zeroes to become 123.
I've had a look at trim and substr but I don't believe these will do the job?
You can use ltrim() and pass the characters that should be removed as second parameter:
$input = ltrim($input, '0');
// 000123 -> 123
ltrim only removes the specified characters (default white space) from the beginning (left side) of the string.
ltrim($usernumber, "0");
should do the job, according to the PHP Manual
$number = "004561";
$number = intval($number, 10);
$number = (string)$number; // if you want it to again be a string
You can always force PHP to parse this as an int. If you need to, you can convert it back to a string later
(int) "000123"
You can drop the leading zeros by converting from a string to a number and back again. For example:
$str = '000006767';
echo ''.+$str; // echo "6767"
Just multiply your number by zero.
$input=$input*1;
//000000123*1 = 123