PHP: Remove and Prepend zeros in a string

So in a recent project, the hardware being used was sending data always prepended with the zeros. I was using this as a number in my database, so this is what I did for removing the leading zeroes from the string

$str = ltrim($str, '0');

So if you do something like

$str = '000000012'
$str = ltrim($str, '0'); // '12'
echo $str; // prints 12

Adding leading zeroes

Given that the value is in $value, the following code will make the total length of string to be eight, adding the needed leading zeroes accordingly.

To simply print/ echo it:

printf("%08d", $value);

To put it in a variable and use it later:

$formattedValue = sprintf("%08d", $value);
echo $formattedValue;
Uncategorized

Notice: Theme without comments.php is deprecated since version 3.0.0 with no alternative available. Please include a comments.php template in your theme. in /var/www/fahdmurtaza.com/public_html/wp-includes/functions.php on line 3984

Leave a Reply

Your email address will not be published. Required fields are marked *