Skip to content

PHP Conditionals & Loops

If…else…else if

Example

<?php
if($a > $b)
echo "a is bigger than b.";
else if($a == $b)
echo "a is equal to b";
else
echo "a is smaller than b";
?>

for

Example

<?php 
$my_blog = array("php","js","mysql","ajax");
for($i=0;$i<count($my_blog);$i++)
{
echo $my_blog[$i];
}
//printing array using a for loop
?>

foreach

Example

<?php
$my_blog = array("one"=>"php", "two"=>"js", "three"=>"mysql", "four"=>"ajax");
foreach($my_blog as $key=>$value)
{
echo $key." is key.";
echo "<br>";
echo $value." Is value";
echo "<br><br>";
}

//printing array elements using foreach
?>

switch

Example

<?php
switch($course)
{
case "php":
echo "You have selected PHP";
break;

case "javascript":
echo "You have selected Javascript";
break;

case "ajax":
echo "You have selected Ajax";
break;

case "mysql":
echo "You have selected MySQL";
break;

default:
echo "Please select a course to complete";
}
?>

while

Example

<?php
	$poss = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY
	Z1234567890";
$i=0; While($i<10)
{
$code .= substr($poss, mt_rand(0,strlen($poss) -1), 1);
$i++;
}

echo $code;
?>

do-while

Example

<?php
	$poss = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY
	Z1234567890";
$i=0;
do
{
$code .= substr($poss, mt_rand(0,strlen($poss)-1) , 1);
$i++;
}
while($i<10);

echo $code; ?>

<< Back

PHP Array & Strings

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: