Jump to content

Recommended Posts

hi im looking at this code and im trying to udnerstand it

 

i know it prints hello world 5 times but

 

and it goes (initialization, conidtion,increment) but i really need someone to dumb it down for me if they could

 

i undersatnd the conidtion thats imple maths but the initilaiztion and the increment how do they work and sutff?

 

Cheers

 

<html>
<body><?php
for ($i=1; $i<=5; $i++)
{
  echo "Hello World!<br />";
}
?></body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/98328-for-loops-trying-to-understand/
Share on other sites

for (start with $i equals 1; do what is between curled brackets while $i is lesser or equals to 5; after doing what is in the barckets add 1 to $i )

{

  echo "Hello World!<br />";

}

 

That is incorrect.

for(  $i = 0   ;                                         $i <= 5                         ;                      $i++                      )
for(set $i to 1; if the condition is true (in your case if $i is less than or equal to 5); then increment $i and execute code in the braces)

Ok I'll give you a breakdown.

 

For loops are controlled by the 3 expressions you see.

 

$i = 1; // first expression

$i<=5; // second expression

$i++; // third expression

 

First your saying that the control variable $i will start at the value 1.

 

It could start at any value you like, in fact it could be any variable you like too such as $x or $zebidee as long as its value is one you can control with the other two expressions.

 

This as you guessed is the initialisation expression.

 

The second expression, $i <= 5; means that the loop must only loop if the value of $i is less than or equal to 5.

 

This condition expression can also be different to what we see here, it could be $i < 2; which would cause our current loop to loop only once because $i = 1, and therefore $i must be less then 2, (1 or 0) so loop once.

 

The third and final part basically says, take the value of $i and now add 1 to it. Or $i = $i + 1;

 

The loop will then fire and go back to the condition statement. It will ignore the initialisation statement because $i already exists.

 

$i is now 2 because we incremented it on that previous loop using $i++; It will then re-evaluate the value against the condition so is 2 less than or equal to 5? The answer is yes, so move onto the increment statement $i++ ($i = $i + 1 or 3 = 2 + 1)

 

The loop will fire again and keep re-evaluating until finally the condition fails (when $i is no longer less than or equal to 5, when it becomes 6) at which point it will exit the loop.

ok thanks, i think of got it now but i still cant figure this out...

 

what the below does it print each 'PortTitle' 3 times and move to the next row and do the same for all the other records

i want the rows to increment after portitle has been displayed in a row 3 times

 

so

title 1 | title 2 | title 3

title 4 | title 5 | title 6

title 7 | title 8 |

 

<?php

include($_SERVER['DOCUMENT_ROOT'] . '/includes/connection.php');

$res = mysql_query("SELECT * FROM tblPortfolio WHERE PortType='Web' ORDER BY PortDateAdded DESC") or die(mysql_error());
$data="";

$data .="<table><tr>"."\n";
while($row=mysql_fetch_array($res))  {

for ($i=1; $i<=3; $i++){
$data .="<td>". $row['PortTitle']."</td>"."\n";
}      

$data .="</tr><tr>"."\n";   
}
$data .="</tr></table>"."\n";   
echo $data;
?>

 

Before we can really help, you, please execute this code and paste the output so we can see the kinda data you're working with:

 

 

<?php

while($row=mysql_fetch_array($res))  {

$a[] = $row;

}

echo '<pre>';
print_r($a);
echo '</pre>';

?>

that code gave this...

 

Array
(
    [0] => Array
        (
            [0] => 5
            [PortID] => 5
            [1] => Vivergo Fuels
            [PortTitle] => Vivergo Fuels
            [2] => asdkjasdklj
            [PortSub] => asdkjasdklj
            [3] => Web
            [PortType] => Web
            [4] => VIV1.png
            [PortImage1] => VIV1.png
            [5] => VIV2.png
            [PortImage2] => VIV2.png
            [6] => VIV3.png
            [PortImage3] => VIV3.png
            [7] => asdas
as
das
d
asd

            [PortDetails] => asdas
as
das
d
asd

            [8] => 30/03/08
            [PortDateAdded] => 30/03/08
        )

    [1] => Array
        (
            [0] => 4
            [PortID] => 4
            [1] => Construction Works
            [PortTitle] => Construction Works
            [2] => asdfhjsdfajhsdfsdf
            [PortSub] => asdfhjsdfajhsdfsdf
            [3] => Web
            [PortType] => Web
            [4] => ConsW1.png
            [PortImage1] => ConsW1.png
            [5] => ConsW2.png
            [PortImage2] => ConsW2.png
            [6] => ConsW3.png
            [PortImage3] => ConsW3.png
            [7] => asdasd
asd
asd
asd
as
das
            [PortDetails] => asdasd
asd
asd
asd
as
das
            [8] => 29/03/08
            [PortDateAdded] => 29/03/08
        )

    [2] => Array
        (
            [0] => 3
            [PortID] => 3
            [1] => City Works
            [PortTitle] => City Works
            [2] => asldhasldhask
            [PortSub] => asldhasldhask
            [3] => Web
            [PortType] => Web
            [4] => CityW1.png
            [PortImage1] => CityW1.png
            [5] => CityW2.png
            [PortImage2] => CityW2.png
            [6] => CityW3.png
            [PortImage3] => CityW3.png
            [7] => sdasdasdasd
asdas
dasd
asd
asd
            [PortDetails] => sdasdasdasd
asdas
dasd
asd
asd
            [8] => 28/03/08
            [PortDateAdded] => 28/03/08
        )

    [3] => Array
        (
            [0] => 2
            [PortID] => 2
            [1] => Design Development Solutions Ltd
            [PortTitle] => Design Development Solutions Ltd
            [2] => asdasad
            [PortSub] => asdasad
            [3] => Web
            [PortType] => Web
            [4] => DDS1.png
            [PortImage1] => DDS1.png
            [5] => DDS2.png
            [PortImage2] => DDS2.png
            [6] => DDS3.png
            [PortImage3] => DDS3.png
            [7] => asdasdasdasdasdasdasd
            [PortDetails] => asdasdasdasdasdasdasd
            [8] => 27/03/08
            [PortDateAdded] => 27/03/08
        )

    [4] => Array
        (
            [0] => 1
            [PortID] => 1
            [1] => Fast Track Karting
            [PortTitle] => Fast Track Karting
            [2] => Hulls Prermier Karting Arena
            [PortSub] => Hulls Prermier Karting Arena
            [3] => Web
            [PortType] => Web
            [4] => FT1.png
            [PortImage1] => FT1.png
            [5] => FT2.png
            [PortImage2] => FT2.png
            [6] => FT3.png
            [PortImage3] => FT3.png
            [7] => design inasdasd
asdasd
asd
as
dasd
asd
            [PortDetails] => design inasdasd
asdasd
asd
as
dasd
asd
            [8] => 26/03/08
            [PortDateAdded] => 26/03/08
        )

)

 

 

Okay, so my assumption is you just want to list portTitle's out in a 3 column layout?

 

Try this code:

 

<?php

include($_SERVER['DOCUMENT_ROOT'] . '/includes/connection.php');

// Restrict our query to only the data we want. No sense in wasting memory on stuff we dont need
// Also goo pratcise to backtick (`) all mysql tables and columns
$res = mysql_query("SELECT `portTitle` FROM `tblPortfolio` WHERE `PortType`='Web' ORDER BY `PortDateAdded` DESC") or die(mysql_error());

// Set a new variable that keeps track of the current column.
$col = 1;
// Set a new vairable defining how many columns we want
$colMax = 3;

// Start the table
echo "<table border=\"1\">\n";
// mysql_fetch_assoc only returns an associative array, rather than both numeric and associative.
// this is to save a bit of memory as well
while($row=mysql_fetch_array($res))  {

// check if this is the first column
 if ($col == 1)
	// if it is the first row, echo the html
	echo " <tr>\n";

// Echo the data as usual
echo "  <td>$row['portTitle']</td>\n";

// Check to see if the row is equal to $colMax (meaning this is the last column)
if ($col == $colMax) {
	// If it is, echo the ending html and reset $col to start over
	echo " </tr>\n";
	$col = 1;
// Otherwise, increment $col and move on to the next entry
} else
	$col++;

}

// Now here's the trick. Imagine you have 8 results.
// 8/3 doesn't go well, you'll be left with a blank
// column that won't be echo'ed. We dont want that.
// But thankfully we've tracked our current column,
// and can filll the rest with blank cells

// Loop until $col > $colMax, but not if $col = 1 (in the
// above loop, $col is set to 1 after a </tr> is echo'ed,
// so it would mean clean results). Also, in the above loop
// if we ended on the second column, $col would iterate at
// the end with a value of 3 even though we are left with an
// empty cell... this is why we use <=
while ($col <= $colMax && $col !== 1) {

// Echo blank cell
echo "  <td> </td>\n";
// Increment column by 1.. if this is that last one, it will
// define it as $colMax + 1
$col++;

// Once again, check if this is the last column. 
if ($col > $colMax)
	// If it is, echo the ending html
	echo " </tr>\n";

}

// Finally, echo the closing table
echo "</table>\n";
?>

 

I usually don't like to code for people, but you show an honest attempt to learn and understand. If there's anyting in this script you don't understand, letm e know and i'll explain further.

 

Oh and you can replace the echo's with $data .= and it will work just as you had it before.

Boy am i silly... replace

 

while($row=mysql_fetch_array($res))

 

with

 

while($row=mysql_fetch_assoc($res))

 

------------------------

 

or alternately, you could use

 

while($row=mysql_fetch_row($res))

 

and then you would call $row[0] instead of $row['portTitle']. This save a tiny bit of memory, but I usually don't use it, as it is a little less convenient, especially using SELECT * where you don't define the order of the rows.

 

------------------------

 

Glad I could help though. Everyone's a beginner at some point. I'm just glad you actually asked for guidance and not 'heres the code find the error, tell me where to put it'

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.