How to remove zero before number in PHP?

by dalton_moen , in category: PHP General , 2 years ago

How to remove zero before number in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by darion , 2 years ago

@dalton_moen you can cast it to integer to remove zero before any number in PHP, code:


1
2
3
4
5
6
<?php

$num = '025';

// Output: 25
echo (int) $num;


Member

by brandy , 8 months ago

@dalton_moen 

You can remove leading zeros from a number in PHP using the ltrim() function. The ltrim() function is used to remove leading characters from a string.


Here is an example of how to remove leading zeros from a number:

1
2
3
$number = "00123";
$number = ltrim($number, "0");
echo $number;


Output:

1
123


In the above example, the ltrim() function is used to remove the leading zeros from the $number string. The first argument of the ltrim() function is the string that you want to modify, and the second argument is the characters that you want to remove from the beginning of the string. In this case, we want to remove the leading zeros, so we pass "0" as the second argument.


After calling ltrim($number, "0"), the value of the $number variable will be updated to "123", and that is what will be echoed.