All About Conditions
By admin • Apr 16th, 2008 • Category: 1.2. Code BasicsI thought it relevent as a beginner to get a run-through of some conditional statements you can use with PHP.
The If Condition
<?php
if($some_variable == 1){
//do something
} //end if
?>
The If Else Condition
<?php
if($some_variable == 1){
//do something
} else {
//do something else
} //end if/else
?>
The Switch Condition
The switch is used when you have one variable and want to compare it to many different values. While this could be done with an if statement, you get a performance increase by using a switch statement because PHP goes either directly to the case or the default clause, as apposed to the equivalent if statement where it needs to go through each clause until it finds a match. Probably more than you needed to know
Here is the syntax:
<?php
switch($some_variable){
case 1:
echo 'value is 1';
break;
case 2:
echo 'value is 2';
break;
default:
echo 'value is not 1 or 2';
} //end switch
?>
The While Condition
<?php
//count to 10
$i = 1;
while($i <= 10){
echo $i;
$i++; //equivalent of i = i + 1
} //end while
?>
Or the equivalent for statement:
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
?>
The Foreach Condition
<?php
//loop through an array's elements
$some_array = array(1,2,3);
foreach($some_array as $key => $value){
echo $key.'s value is: '.$value;
} //end foreach
?>
admin is
Email this author | All posts by admin
