问题
I know I have done this in Javascript once, but how can I make it in PHP? Basically I want to do this:
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.
回答1:
why the extra if into the while? i would do this:
$counter = 0;
while(...)
{
(...)
$counter++;
}
echo $counter;
回答2:
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.
$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($counter < 10){
echo "plus one to $counter";
$counter++;
}
echo("Counter is $counter!"); // Outputs: Counter is 10!
回答3:
You're going to have to learn the basics of how PHP outputs to the screen and the other controls along with it.
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 echo
statements.
Also, when dealing with echo
statements, notice the difference between single quotes and double quotes. Double quotes will process any contained variables:
$counter = 3;
echo "plus one to $counter"; // output: plus one to 3
echo 'plus one to $counter'; // output: plus one to $counter
来源:https://stackoverflow.com/questions/11869142/how-can-i-make-a-php-counter