How does php return four digits and add zeros if they are not enough?

青灯夜游
Release: 2023-03-15 16:30:02
Original
2370 people have browsed it

In PHP, you can use the str_pad() function to return four digits, and add zeros if there are less than four digits. The syntax is "str_pad($num,4,"0",STR_PAD_RIGHT)"; the parameter "STR_PAD_RIGHT" is specified Pad zeros on the right side of a numeric string.

How does php return four digits and add zeros if they are not enough?

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In php, you can use str_pad () function to return four digits, if less than four digits are filled with zeros.

Example:

<?php
echo str_pad(128,4,"0",STR_PAD_RIGHT)."<br>";
echo str_pad(12,4,"0",STR_PAD_RIGHT)."<br>";
echo str_pad(1283,4,"0",STR_PAD_RIGHT)."<br>";
?>
Copy after login

How does php return four digits and add zeros if they are not enough?

Explanation:

str_pad() function can use specified characters to The string is padded to the new length.

Syntax:

str_pad(string,length,pad_string,pad_type)
Copy after login
ParametersDescription
string

Required. Specifies the string to be filled.

lengthRequired. Specifies the length of the new string. If the value is less than the length of the original string, no operation is performed.
pad_string Optional. Specifies the string used for padding. The default is blank.
pad_type Optional. Specifies which side of the string to fill.

Possible values:

  • STR_PAD_BOTH - Pad both sides of the string. If it's not an even number, the right side gets extra padding.
  • STR_PAD_LEFT - Pad the left side of the string.
  • STR_PAD_RIGHT - Pad the right side of the string. This is the default.

Example:

<?php
echo str_pad(128,4,"0",STR_PAD_RIGHT)."<br>";
echo str_pad(128,4,"0",STR_PAD_LEFT)."<br>";
echo str_pad(12,4,"0",STR_PAD_BOTH)."<br>";
?>
Copy after login

How does php return four digits and add zeros if they are not enough?

Recommended learning: "PHP Video Tutorial

The above is the detailed content of How does php return four digits and add zeros if they are not enough?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!