Page 1 of 1

Basic foreach help

Posted: Mon Feb 02, 2009 7:23 am
by lazystudent
I would like so help with creating a basic table that has numbers 1 - 27 on one column and letters a - z on the other, but i want it created by foreach or a loop,

can anyone supply me with code for this

Re: Basic foreach help

Posted: Mon Feb 02, 2009 7:34 am
by papa

Code: Select all

 
<table border="1">
<?php
$letters = range('a', 'z');
 
for($i=0; $i<count($letters); $i++) {
    echo "<tr>\n";
    echo "<td>".$i."</td> ";
    echo "<td>".$letters[$i]."</td>\n";
    echo "</tr>\n";
}
 
?>
</table>
 
What you need to do now is to figure out how to display 1-26 instead 0-25.

Re: Basic foreach help

Posted: Mon Feb 02, 2009 12:04 pm
by lazystudent
So that'll do a to z but how do you create a column going 1 to 27 next to it

Re: Basic foreach help

Posted: Mon Feb 02, 2009 12:08 pm
by Mark Baker
lazystudent wrote:So that'll do a to z but how do you create a column going 1 to 27 next to it
If you used the code that was posted, you should get 0..25 in a column. It's up to you to modify it to get 1..26 instead.

But why to 27? There isn't a 27th letter of the alphabet in English.

Re: Basic foreach help

Posted: Tue Feb 03, 2009 2:45 am
by lazystudent
I have pasted this into notepad ++ but it has come up with

"; echo " ".$letters[$i]." \n"; echo "
\n"; } ?>

This isn't a table with letters down 1 side and numbers on another, am i doing something wrong

Re: Basic foreach help

Posted: Tue Feb 03, 2009 2:48 am
by papa
You are really a lazy student arent you ? :)

Have you installed php on your computer?

Re: Basic foreach help

Posted: Tue Feb 03, 2009 3:06 am
by lazystudent
LOL i had no idea i had to install PHP i just downloaded and installed it

should that make a difference

Re: Basic foreach help

Posted: Tue Feb 03, 2009 3:09 am
by papa
What happens when you type "localhost" in your browser's address field?

Re: Basic foreach help

Posted: Tue Feb 03, 2009 4:40 am
by lazystudent
i got it working!!

but now i've been told you use

<?foreach (range(1, 30) as $temp_number) {
echo "$temp_number<br>";
}?>

this in the code

Re: Basic foreach help

Posted: Tue Feb 03, 2009 5:50 am
by papa
Ok, whatever works for you :)

So your alphabet is 30 characters long ?

Re: Basic foreach help

Posted: Tue Feb 03, 2009 11:43 am
by Skoalbasher
lol.

Try this.

Code: Select all

 
<table border="1">
<?php
$letters = range('a', 'z');
 
$j = 1;
for($i=0; $i<count($letters); $i++) {
    echo "<tr>\n";
    echo "<td>".$j."</td> "; // here should work?
    echo "<td>".$letters[$i]."</td>\n";
    echo "</tr>\n";
    $j++;
}
 
?>
</table>