7

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
  • 1
    What do you mean by it didn't work?
    – andrewsi
    Aug 8, 2012 at 16:39

3 Answers 3

17

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

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

echo $counter;
0
4

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!
2

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
2
  • The echo was just to explain. I know PHP basics, this was just a quick post so that I could fix my function.
    – imp
    Aug 8, 2012 at 16:46
  • 1
    Gotcha. Just wanted to help kick-start you if you didn't know. (: Aug 8, 2012 at 16:47

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.