Forum Moderators: coopster

Message Too Old, No Replies

Specify integer length

         

Readie

11:17 pm on Dec 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi,

Because I got such good help here last time I had a query, I thought I would post my problem here again :)

I'm assisting to make a website, and a simple hit counter is wanted, now I'm using a text file hit counter with the code:

<?php
$counttxt = ("counter.txt");
$hits = file($counttxt);
$hits[0] ++;
$fp = fopen($counttxt, "w");
fputs($fp, $hits[0]);
fclose($fp);
echo '<p class="small">There have been ' . $hits[0] . ' page hits since 20/12/2009</p>';
?>

with

include ("counter.php");

To display it

Which works completely fine save for one minor cosmetic detail. I want it to have a minimum number of digits in the output (so it would read "0001" as opposed to just "1") but not simply have a crude

echo '000' . $hits[0];

As at higher numbers that would need manual trimming.

Is this possible? And if so, how?

Regards,

Readie

Readie

11:30 pm on Dec 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



*Note*

Since posting this I've had a quick think and realised that something along the lines of:

if($hits < 10)
{
$num = '000';
}
else if($hits < 100)
{
$num = '00';
}
else if($hits < 1000)
{
$num = '0';
}
else
{
$num = '';
}
echo '<p class="small">There have been ' . $num . $hits[0] . ' page hits since 20/12/2009</p>';

Would work, however that seems a very inefficient method.

ALKateb

11:53 am on Dec 21, 2009 (gmt 0)

10+ Year Member



you can do it using printf() function

printf("%04s",$hits[0]);

Readie

4:22 pm on Dec 21, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks very much :)