John Davidson

How to add in PHP without causing the starting 0s to vanish

0 comments
Message:


I have 2 php variables :


$oldnum = 00000497;
$newnum = 00002318;

when i do this echo $oldnum + $newnum; it gives me the value 2815 but i want value to come with initial 0s like this : 00002815


Is there any way i can achieve this??



My Answer:
Yes, you can achieve this by using the `str_pad` function in PHP. Here's how you can add the two variables without causing the starting 0s to vanish:

php
$oldnum = "00000497";
$newnum = "00002318";

$result = str_pad($oldnum + $newnum, strlen($oldnum), "0", STR_PAD_LEFT);

echo $result; // Output: 00002815


In this code snippet, `str_pad` is used to add leading zeros to the result of adding `$oldnum` and `$newnum`. The `strlen($oldnum)` parameter specifies the total length of the resulting string, and the `"0"` parameter specifies the character to use for padding. `STR_PAD_LEFT` specifies that the padding should be added to the left side of the string.

Rate this post

4 of 5 based on 4699 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us