Home >Backend Development >PHP Problem >How does php return four digits and add zeros if they are not enough?

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

青灯夜游
青灯夜游Original
2022-03-18 19:29:482441browse

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>";
?>

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)
Parameters Description
string

Required. Specifies the string to be filled.

length Required. 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>";
?>

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!

Statement:
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