简体   繁体   English

在 PHP 中添加带有字符串的回声?

[英]Adding an echo with a string in PHP?

I have an echo = "000000" and a string named $id which is an integer.我有一个 echo = "000000" 和一个名为 $id 的字符串,它是一个 integer。

If $id is = 1, how do I add "000000" + $id to get 000001?如果 $id = 1,如何添加“000000”+ $id 得到 000001?

You could check out str_pad你可以看看str_pad

In your case it would be something like:在您的情况下,它将类似于:

str_pad('1', 6, '0', STR_PAD_LEFT);
function padWithZeros($s, $n) {
  return sprintf("%0" . $n . "d", $s);
}

Where $n is the number of zeros you want, eg:其中 $n 是您想要的零的数量,例如:

echo padWithZeros("1", 6);

That pads the number 1 with five zeros to equal six places用五个零填充数字 1 等于六个位置

printf("%06d", $id)

$temp = "00000".$id; $temp = "00000".$id; echo "ID = $temp";回声“ID = $temp”;

str_pad is the PHP function that does exactly what you want. str_pad 是 PHP function 完全符合您的要求。 However, printf is a well understood method of doing that that works across most common languages.但是,printf 是一种很好理解的方法,适用于大多数常用语言。 It probably makes sense to use printf in this case to make the code more readable.在这种情况下使用 printf 使代码更具可读性可能是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM