Halo! I am not sure where I am going wrong in my switch statement! Here's what I want my code to do:
If all three variables are empty, then I want nothing to happen. However, if not, then I want to see which ones are empty and which ones are not and perform different tasks based on their state.
If they're not empty then I want to add a string before the variable. If they're empty, then I want to add a string stating "..PLEASE PROVIDE INFORMATION".
With the current hard coded variables, it should return:
Airline Name: United
Flight Number: 262
Departure Airport: PLEASE PROVIDE DEPARTURE AIRPORT
but it returns:
Airline Name: PLEASE PROVIDE AIRLINE NAME
Flight Number: PLEASE PROVIDE FLIGHT NUMBER
Departure Airport: PLEASE PROVIDE DEPARTURE AIRPORT
Code:
$airline_name = "United";
$flight_number = 262;
$departure_airport = "";
function airport($one, $two, $three) {
if ($one =="" && $two =="" && $three =="") {
} else {
switch(true) {
case !empty($one):
$one = "Airline Name: $one<br>";
case empty($one):
$one = "Airline Name: PLEASE PROVIDE AIRLINE NAME<br>";
case !empty($two):
$two = "Flight Number: $two<br>";
case empty($two):
$two = "Flight Number: PLEASE PROVIDE FLIGHT NUMBER<br>";
case !empty($three):
$three = "Departure Airport: $three<br>";
case empty($three):
$three = "Departure Airport: PLEASE PROVIDE DEPARTURE AIRPORT<br>";
}
}
echo $one, $two, $three;
}
airport($airline_name,$flight_number,$departure_airport);
?>
The behavior you want would be achieved with an if else
, or the ternary operator (which is pretty much just a short hand way of writing an if/else
). Here's a rough untested example.
function airport($one, $two, $three) {
if ( !empty($one) || !empty($two) || !empty($three) ) {
$one = !empty($one) ? "Airline Name: $one<br>" :"Airline Name: PLEASE PROVIDE AIRLINE NAME<br>";
$two = !empty($two) ? "Flight Number: $two<br>" : "Flight Number: PLEASE PROVIDE FLIGHT NUMBER<br>";
$three = !empty($three) ? "Departure Airport: $three<br>" : "Departure Airport: PLEASE PROVIDE DEPARTURE AIRPORT<br>";
}
echo $one, $two, $three;
}
airport($airline_name,$flight_number,$departure_airport);
As to why your switch
doesn't perform as you expect, per the manual:
Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments