The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

> PHP Question - Small Script
Aush
post Mar 24 2012, 07:37 PM
Post #1


Novice
**

Group: Members
Posts: 25
Joined: 8-February 10
Member No.: 11,027



I have a very small script that I need help with. I'm learning PHP, and I can't figure out why this loop won't work. Please help! =]

Here it is:

<?PHP
$counter = 0;
$start = 1;

for($start; $start < 11; $start++) {
$counter = $counter++;
print $counter . "<BR>";
}

?>

It DOES work when I do this, however:

<?PHP
$counter = 0;
$start = 1;

for($start; $start < 11; $start++) {
$counter = $counter + 1;
print $counter . "<BR>";
}

?>

I bolded the difference between the two. Thank you very much.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
 
Reply to this topicStart new topic
Replies
Aush
post Mar 25 2012, 01:13 PM
Post #2


Novice
**

Group: Members
Posts: 25
Joined: 8-February 10
Member No.: 11,027



Thank you for the response. smile.gif

I still have a question, though. Even if $counter is incremented after using it, shouldn't it still add 1 each time, since it's looping?

I don't see why it makes a difference whether it's used before or after.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Ephraim F. Moya
post Mar 25 2012, 01:55 PM
Post #3


Advanced Member
****

Group: Members
Posts: 167
Joined: 2-September 07
From: New Mexico
Member No.: 3,702



QUOTE(Aush @ Mar 25 2012, 11:13 AM) *

Thank you for the response. smile.gif

I still have a question, though. Even if $counter is incremented after using it, shouldn't it still add 1 each time, since it's looping?

I don't see why it makes a difference whether it's used before or after.


Because $counter = $counter++ IS ALWAYS ZERO!

You might be interested in this more efficient way of writing your loop:

<?php

for( $start = 1, $counter = 0; $start < 11; $start++ )
{
echo "{$counter++}. <br>";
}

or:

for( $start = 0, $counter = 0; $start < 10; echo "{$counter++} <br>", $start++);


This post has been edited by Ephraim F. Moya: Mar 25 2012, 02:54 PM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Posts in this topic


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 29th March 2024 - 05:37 AM