• Welcome to ForumKorner!
    Join today and become a part of the community.

reGi's PHP Beginner Series Part 3

reGi

User is banned.
Reputation
0
reGi’s PHP Beginner Series Part 3

While Loops

We can use while loops if we need to execute code more than once. There are 2 types of while loops, while, and do while. Do while will always execute the code at least once no matter what and then continue executing the code if the condition is still true.

While Example:
PHP:
<?php

$i=1;
while($i<=3)
{
	echo “Number: “.$i.”<br />”;
	$i++;
}
/*This will output:
Number:1
Number:2
Number:3*/

?>

Do While Example:
PHP:
<?php

$i=1;
do
{
	Echo “Number:”.$i.”<br />”;
	$i++
}
while ($i<=3);
/*This will output:
Number:1
Number:2
Number:3*/


?>

As you can see they are very similar, except that do while will always execute at least once.

For Loop

We can use For loops to execute code a specific amount of times. There are also 2 types of for loops, for, and foreach. The foreach loop will loop through arrays, and the for loop will loop through code a specific amount of times.

For Loop Example:
PHP:
<?php

for($i=1; $i<=3; $i++)
{
	echo “Number:”.$i.”<br />”;
}

/*This will output:
Number:1
Number:2
Number:3*/

?>

Foreach Loops Example:
PHP:
<?php

$array=array(“1”, “2”, “3”);

foreach($item in $array)
{
	echo “Number:”.$item.”<br />”;
}

/*This will output:
Number:1
Number:2
Number:3*/

?>

Functions

Functions can be created and the code inside them will not be executed until called. You can have functions with parameters and functions without. They can also return a value which may be better in some cases.

Example 1:
PHP:
<?php

function myName()
{
	echo “reGi”;
} 

echo “Hi! I am “;
myName();

//Will output Hi! I am reGi

?>

Example 2:
PHP:
<?php

function myName()
{
	return “reGi”;
}

echo “Hi! I am “.myName();

//Will output Hi! I am reGi

?>

Example 3:
PHP:
<?php

function getTotal($a, $b)
{
	$total=$a+$b;
	return $total;
}

echo “1+3=”.getTotal(1, 3);

//Will output 1+3=4

?>

Thanks for reading! This is the end of part 3 of the PHP Beginner Series. I said this might be the last part of the beginners series but have decided to make another otherwise this one would have been to long if I added more into this one! Part 4 will cover Forms, $_POST and $_GET.

Note: most code is a simplified version of W3Schools.com code, I recommend you check out their site for more PHP information.
 

Legend_mybb_import1694

Active Member
Reputation
0
Very nice, I like how you simplify the programming guides. I understand more from you than from W3Schools when it comes to understanding.
 

reGi

User is banned.
Reputation
0
Indelibleâ„¢ said:
Very nice, I like how you simplify the programming guides. I understand more from you than from W3Schools when it comes to understanding.

Thank you!! Glad im helping :D Can't wait to finish beginner series and write some funner tutorials! :)
 
Top