如何制作 PHP 计数器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11869142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:19:04  来源:igfitidea点击:

How can I make a PHP counter?

phpcountcounter

提问by imp

I know I have done this in Javascript once, but how can I make it in PHP? Basically I want to do this:

我知道我曾经在 Javascript 中做过这个,但是我怎样才能在 PHP 中做到呢?基本上我想这样做:

if (empty($counter)){
   $counter = 1;
}else{
   "plus one to $counter" ($counter++?)
}

But it didn't work when I tried. How would I go about doing this?

但是当我尝试时它不起作用。我该怎么做呢?

Thank you :)

谢谢 :)

EDIT: This is so I can do:

编辑:这是我可以做的:

if ($counter == 10){
   echo("Counter is 10!");
}

EDIT:

编辑:

This is all in a "while()" so that I can count how many times it goes on, because LIMIT will not work for the query I'm currently doing.

这一切都在“while()”中,以便我可以计算它进行了多少次,因为 LIMIT 不适用于我当前正在执行的查询。

回答by Jarry

why the extra if into the while? i would do this:

为什么额外的 if 进入 while ?我会这样做:

$counter = 0;
while(...)
{
    (...)
    $counter++;
}

echo $counter;

回答by RobB

To increment a given value, attach the increment operator ++to your integer variable and place it within your while loop directly, without using a conditional expression to check if the variable is set or not.

要递增给定值,请将递增运算符附加++到整数变量并将其直接放入 while 循环中,而不使用条件表达式来检查变量是否已设置。

$counter = 1;

while(...){
    echo "plus one to $counter";
    $counter++;
}

If your counter is used to determine how many times your code is to be executed then you can place the condtion within your while()expression:

如果您的计数器用于确定您的代码要执行的次数,那么您可以将条件放在您的while()表达式中:

while($counter < 10){
    echo "plus one to $counter";
    $counter++;
}

echo("Counter is $counter!");  // Outputs: Counter is 10!

回答by Tango Bravo

You're going to have to learn the basics of how PHP outputs to the screen and the other controls along with it.

您将必须学习 PHP 如何输出到屏幕和其他控件的基础知识。

if (empty($counter)){
   $counter = 1;
}else{
   echo 'plus one to $counter';
   $counter++;
}

Something along those lines will work for you.

沿着这些路线的东西对你有用。

PHP is pretty flexible with what you throw at it. Just remember, statements need a semicolon at the end, and if you want to output to the screen, (in the beginning) you'll be relying on echostatements.

PHP 对你投入的东西非常灵活。请记住,语句末尾需要一个分号,如果您想输出到屏幕,(一开始)您将依赖于echo语句。

Also, when dealing with echostatements, notice the difference between single quotes and double quotes. Double quotes will process any contained variables:

另外,在处理echo语句时,请注意单引号和双引号之间的区别。双引号将处理任何包含的变量:

$counter = 3;
echo "plus one to $counter"; // output: plus one to 3
echo 'plus one to $counter'; // output: plus one to $counter