7th December 2015
In
PHP
PHP if/else and switch
In this post we will:
- Demonstrate how to use an if/else statement
- Evaluate and justify when and demonstrate how to use a switch statement
- Combine variables and operators to create more complex conditions and outcomes
What are conditional statements?
- Conditional or if/else statements test a variable or value against a set parameter
- If a condition is met it is set to true and code is executed based on that outcome
- If not another passage of code is executed
In Flow Form – How if/else works
If/Else in practice
$instructorsName = "Toby"; $studentName = "Jocelyn"; if($instructorsName == "Toby") { echo "Hi $instructorsName - you are teaching PHP and MySQL today!"; } else { echo "Welcome to the PHP5 and MySQL course $studentName!"; }
Output would be:
Hi Toby - you are teaching PHP and MySQL today!
Switch or Case Statement
So, what your a case statement be in flow form?
Hang on – isn’t that the same as if/else?
What’s the point of that?
Why use switch?
- Reduces lengthy and unwieldy if/else statements
- Neater more legible code so easy to update and maintain
- Less demand on the server
- Greater control over error handling
Tip: Only use switch if you have more than four conditions
Switch in practice
$weekday = "Tuesday"; switch($weekday) { case 'Sunday' : echo "Day off!"; break; case 'Monday' : echo "Admin day"; break; case 'Tuesday' : echo "Evening course"; break; case 'Wednesday' : echo "Interactive Media year one"; break; case 'Thursday' : echo "Interactive Media year two"; break; case 'Friday' : echo "PHP Course HND Computer Science"; break; case 'Saturday' : echo "Morning workshop"; break; default : echo "The day you have put in is not valid!
"; exit(); } //echo "
This code is executed if none of the conditions of the switch statement have been met";
Try this task
Task: Create a simple if/else condition based on the previous examples in this lesson and also demonstrate how to use a switch statement. Test outcomes in a browser.
Build:
A pricing condition that adds a carriage fee £15 to any product less than a value of £100.
Also build a switch statement that adds varying degrees of delivery rates based on value.
In this post we have:
- Demonstrated how to use an if/else statement
- Evaluated and justified when and demonstrated how to use a switch statement
- Combined variables and operators to create more complex conditions and outcomes
No Comments