Home > Backend Development > PHP Tutorial > PHP automatically adds 0 to the left side of numbers_PHP tutorial

PHP automatically adds 0 to the left side of numbers_PHP tutorial

WBOY
Release: 2016-07-21 15:53:28
Original
1022 people have browsed it

Copy the code The code is as follows:

$sourceNumber = "1";
$newNumber = substr (strval($sourceNumber+1000),1,3);
echo "$newNumber";
?>

This time it will appear: 001
If you want To increase the number of digits, you can increase 1000, and then increase 3 as well.
Example: If I want to add "4 zeros", line 03 will look like this.
Copy code The code is as follows:

$newNumber = substr(strval($sourceNumber+100000 ),1,5);
?>

In fact, how many digits do you want to display in total? Just add as many 0s after $sourceNumber+1, and change the last number directly. to display several digits.

A better way:
string str_pad ( string $input, int $pad_length [, string $pad_string [, int $pad_type]] )

Copy the code The code is as follows:

$input = "Alien";
echo str_pad($input, 10); 🎜 >// produces "Alien " "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);
// produces "-=-=-Alien"
echo str_pad($input, 10 , "_", STR_PAD_BOTH);
// produces "__Alien___"
echo str_pad($input, 6, "___");
// produces "Alien_"
?> ; 


Complete the length of the string. Use pad_string to complement. The default is to pad on the right. If STR_PAD_LEFT, pad to the left. STR_PAD_BOTH pads on both sides together.
Use str_pad next time. After all, it is built-in and will definitely be faster than custom one.
/*
I don’t think your method above is very good. Let me introduce a method I wrote. The method function is as follows, so when you want the result 001, the method: dispRepair('1',3,'0')
Function: fill-in function
str: original string
type: type, 0 is back-padded, 1 is front-padded
len: new string length
msg: padding characters
*/

Copy code The code is as follows:
function dispRepair($str,$len,$msg,$type='1') {
$length = $len - strlen($str);
if($length<1)return $str;
if ($type == 1) {
$str = str_repeat($msg,$length).$str;
} else {
$str .= str_repeat($msg,$length);
}
return $str;
}

http://www.bkjia.com/PHPjc/318729.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/318729.htmlTechArticleCopy the code as follows: ?php $sourceNumber="1"; $newNumber=substr(strval($sourceNumber+ 1000),1,3); echo "$newNumber"; ? This time it will appear: 001 If you want to increase the number of digits...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template