I'm having a bit of a problem here. I've checked soo many times for errors and all but I can't get this to work. So I have to create a program which reads 3 lines of input. It's about a grocery shop which has 2 different price values during the week and the weekend. I have to make it output only the price for the fruit * the quantity and if the day or the fruit does not exist output "error". I'm really confused why my code is not working. I've only started PHP, so maybe I just don't have much experience.
$type = strtolower(readline());
$day = strtolower(readline());
$quantity = floatval(readline());
$days = array("monday", "tuesday", "wednesday", "thursday", "friday");
$weekend = array("saturday", "sunday");
$fruit_normal = array(
"2.50" => "banana",
"1.20" => "apple",
"0.85" => "orange",
"1.45" => "grapefruit",
"2.70" => "kiwi",
"5.50" => "pineapple",
"3.85" => "grapes"
);
$fruit_we = array(
"2.70" => "banana",
"1.25" => "apple",
"0.90" => "orange",
"1.60" => "grapefruit",
"3.00" => "kiwi",
"5.60" => "pineapple",
"4.20" => "grapes"
);
$search = array_search($day, $days);
$search1 = array_search($day, $weekend);
$search2 = array_search($type, $fruit_normal);
$search3 = array_search($type, $fruit_we);
if ($search != NULL && $search2 != NULL) {
$price = $search2 * $quantity;
$formatted = number_format($price, 2);
print $formatted;
} elseif ($search1 != NULL && $search3 != NULL) {
$price = $search3 * $quantity;
$formatted = number_format($price, 2);
print $formatted;
} elseif ($search == NULL && $search1 == NULL && $search2 == NULL && $search3 == NULL) {
echo "error";
}
So that's how i solved my problem first i made all of arrays consisting of parameter only to start from 1. And then replaced all of the NULL
values to FALSE
when checking for result from array_search
I'm still not sure what was the real problem but for now I'll accept that's how it is.
$type = strtolower(readline());
$day = strtolower(readline());
$quantity = floatval(readline());
$days = array(1 => "monday", "tuesday", "wednesday", "thursday", "friday");
$weekend = array(1 =>"saturday", "sunday");
$fruit_normal = array(
"2.50" => "banana",
"1.20" => "apple",
"0.85" => "orange",
"1.45" => "grapefruit",
"2.70" => "kiwi",
"5.50" => "pineapple",
"3.85" => "grapes"
);
$fruit_we = array(
"2.70" => "banana",
"1.25" => "apple",
"0.90" => "orange",
"1.60" => "grapefruit",
"3.00" => "kiwi",
"5.60" => "pineapple",
"4.20" => "grapes"
);
$search = array_search($day, $weekend);
$search1 = array_search($type, $fruit_normal);
$search2 = array_search($type, $fruit_we);
$search3 = array_search($day, $days);
if($search1!= FALSE && $search3 != FALSE ){
$price = $search1 * $quantity;
echo number_format($price, 2);
}elseif($search != FALSE && $search2 != FALSE){
$price = $search2 * $quantity;
echo number_format($price, 2);
}elseif($search == FALSE && $search3 == FALSE){
echo "error";
}elseif($search1 == FALSE && $search2 == FALSE){
echo "error";
}