Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a PHP counter?

Tags:

php

count

counter

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.

like image 786
imp Avatar asked Aug 08 '12 16:08

imp


People also ask

How to create counter in PHP?

Depending on server configuration you may need to change the permission for this file to 777 so it is writable by the counter script that we are going to use. Now, lets do the actual PHP code. $count = file_get_contents ( "count. txt" );

What is the use of count () function in PHP?

The count() function returns the number of elements in an array.

What is hit counter in PHP?

PHPGcount is a PHP graphical hit counter. It uses flat-text database so no SQL databases are necessary. It comes with many styles to choose from and you can add your own styles easily!


2 Answers

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

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

echo $counter;
like image 165
Jarry Avatar answered Oct 04 '22 21:10

Jarry


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!
like image 31
Robert Avatar answered Oct 04 '22 21:10

Robert