I have some code that I'd like to add numbers to. I'm using $count=o; with ++$count to generate numbers. They start at "1". How do I get them to start at "0"?

Recommended Answers

All 8 Replies

Sorry. I used the code in text. Doesn't really look like code. Anyway, what I had was:

$count = 0;

With:

++$count

to give me the increment. It started at "1".
I got it working though. Here's what I did:

$num = 0;
$count = --$num;

Now it starts at "0" and I'm happy.
Are there other ways to do this?
By the way, this was for an onClick event for smooth gallery generated from a database.

<?php
$result = mysql_query("SELECT * FROM galleries");
$num = 0;
$count = --$num;
while($row = mysql_fetch_array($result))
echo"<li class=\"indent\"><a onClick=\"myGallery.goTo(".++$count.")\" >".$row['image_name']."</a></li>
";
?>

O.o I have no idea why you would need to do that.

O.o I have no idea why you would need to do that.

Because the onClick event starts with "0":

<li class="indent"><a onClick="myGallery.goTo(0)">1st.jpg</a></li>
<li class="indent"><a onClick="myGallery.goTo(1)">2nd.jpg</a></li>
<li class="indent"><a onClick="myGallery.goTo(2)">3rd.jpg</a></li>
etc.

Well now that the rest of the code is up there I can tell you why you had a problem. You are incrementing count the first time you use it. So when you set $count = 0 , once you got to the echo statement $count became 1 because you are incrementing it already. Instead, you should use $count++ instead. If PHP is like C++ in that respect, the incrementation should occur after the rest of the statement is executed.

every array,

edit lost a bit there

every array starts as array[0]

$count++ works. Tried it yesterday and got errors. Not sure what else I had wrong. That's what I get for working on it so late.

Glad to help. The difference between ++$count and $count++ is that in the first, the variable is incremented before the rest of the statement is interpreted, whereas with the latter, the value is incremented after.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.