Tag: switch

Learning PHP – Step 4 – Statements

In my last post I’ve talked about variables and operators. Now, lets see what can we do with them.

Statement: if

The “if” statement has 3 main forms:





Learning PHP – Step 2


$name = "José Cruz";
$even = 10 % 2;
$odd = 10 % 3;
$someValue = $even * 4;
$ifvar = 1;

// it’s even – simple "if"
if($even == 0) {
echo "10 its even!";
}

// it’s even – simple "if" with an else
if($even == 0) {
echo "10 its even!";
} else {
echo "10 its odd! Really?";
}

// it’s even – complex "if"
if($even == 0) {
echo "10 its even!";
} elseif($ifvar == 1) {
echo "Althougth true, the first branch has already taken the flow! :(";
} elseif($ifvar == 2) {
echo "Just to ensure you understand this construction!";
} else {
echo "10 its odd! Really?";
}
?>

Statement: switch

“switch” it’s a variation of “if”, but for cases where we have some kind of a list of values belonging to a common domain, like: weekdays, months, (1,3,4,5), etc.

The expression inside “switch()” its evaluated and the result will be compared with each of the “case ”. Each “case” can have the “break” statement, which terminates the statement. If its missing, the execution flow goes to the very next “case” (if its valid) until a “break” it’s found.

If a “case ” was not found, then the “default” its used (it it exists).





Learning PHP – Step 2


$weekday = 1; // assuming a week starts on sunday with value 1

switch($weekday) {
case 1:
echo "Sunday";
break;
case 2:
echo "Monday";
break;
case 3:
echo "Tuesday";
break;
case 4:
echo "Wednesday";
break;
case 5:
echo "Thursday";
break;
case 6:
echo "Friday";
break;
case 7:
echo "Saturday";
break;
default:
echo "big mistake1";
}


?>

And that’s it!

Next post about loops!

Technorati Tags: ,,,,,,,
Windows Live Tags: programming,else,switch,if,php,Statements,expression,break
WordPress Tags: programming,else,switch,if,php,Statements,expression,break

Bad Behavior has blocked 82 access attempts in the last 7 days.

Hyper Smash