Is there a simple way to remove a leading zero (as in 01 becoming 1)?
Asked
Active
Viewed 3,573 times
2
-
Does this answer your question? [PHP remove first zeros](https://stackoverflow.com/questions/3563740/php-remove-first-zeros) – drAlberT Jun 14 '23 at 09:10
5 Answers
21
-
While this works in circumstances where you want to remove several leading zeros, in some cases this is not what you want. For example, trying this with a value of "00" would result in "", whereas the intval function suggested below would result in the correct value of "0". – quickthyme Jul 22 '14 at 22:15
8
$str = "01";
echo intval($str);

Tomalak
- 332,285
- 67
- 532
- 628
-
1Maybe it's worth putting an is_numeric() block around it to catch cases where $str is not a number, since intval returns 0 on failure: http://fr.php.net/manual/en/function.intval.php – Michael Stum Dec 01 '08 at 15:36
4
if you use the trim functions, you might mistakenly remove some other character, like by triming "12" your will have "2". use the intval() function. this function will convert your string (which could start by a leading zero or not) to an integer value. intval("02") will be 2 and intval ("32") wll be 32.

farzad
- 8,775
- 6
- 32
- 41
-
However, if you use `intval(011)` for example you will get 9 instead of 11. The right answer is `ltrim($str,"0");` – Waiyl Karim Oct 01 '14 at 01:56
-
1@WaiylKarim: passing 011 to intval() returns 9 because we are passing in numeric 011 which is octal number for 9 (0 indicates octal, 1 * 8 + 1 = 9), which will return decimal 9. But if we pass "011" (a string argument) it will return 11 which is the same as desired result. so: intval(011) -> 9; intval('011') -> 11; :) – farzad Oct 01 '14 at 05:34
-
+1 for your explanation. It's what thought too, however I didn't know that passing it as a string will return the same desired result, I thought it would ignore that. So in this case we can use `ltrim((string)$number, "0"));` to be more secure, because sometimes we do not always retrieve data as string. – Waiyl Karim Oct 01 '14 at 23:03
-1
Just multiply by 1
echo "01"*1

J.D. Fitz.Gerald
- 2,977
- 2
- 19
- 17
-
-
-
The classic, Add-an-aritmetic-calculation-that-doesnt-change-the-original-value-to-make-the-compiler-cast-it-to-a-numeric-value-trick! ;) – Stefan Dec 01 '08 at 15:17
-
@Jeff Atwood: I'm guessing this is a serious answer. So many PHP programmers are self-taught and know how to get the job done, not how to get it done *right*. @J.D. Fitz.Gerald: Sorry that you're being dogged. This really peeves CS people. It's not an explicit solution to the problem. – Lucas Oman Dec 01 '08 at 15:52
-
@epochwolf - why is this not a good way to do this? I have previously advocated $str_value + 0 to convert a number-in-a-string to a number. – staticsan Dec 02 '08 at 05:40