+ 1

Help correct which error of this code

<!--prepared by mohamed nor--> <?php $months = 'Tue'; switch ($months) { case "jan": echo "month is january."; break; case "feb": echo "month is february."; break; case "march": echo "month is march."; break; case "april": echo "month is april."; break; case "may": echo "month is may."; break; case "june": echo "month is june."; break; case "july": echo "month is july."; break; case "agust": echo "month is agust."; break; case "septem": echo "month is setemper."; break; case "october": echo "month is october."; break; case "november": echo "month is november."; break; default: echo "Invalid months."; } ?>

14th Jul 2020, 8:34 PM
Maxamed Nuur Maxamuud
Maxamed Nuur Maxamuud - avatar
2 Réponses
+ 1
That code outputs "Invalid months." when I ran it. An error message would be a more obvious problem. Since there's no really obvious problem, I'll mention some softer, more subjective problems and recommended improvements. The code is useless since it'll always output Invalid months. It could easily get $months populated from a form submission, though. There is a lot of code duplication. The code could be far shorter and still behave the same. Here is a refactor to be shorter: <?php $months = 'Tue'; $valid_months = [ 'jan' => 'january', 'feb' => 'february', 'march' => 'march', 'april' => 'april', 'may' => 'may', 'june' => 'june', 'july' => 'july', 'agust' => 'agust', 'septem' => 'setemper', 'october' => 'october', 'november' => 'november' ]; if (isset($valid_months[$months])) echo 'month is ' . $valid_months[$months] . '.'; else echo "Invalid months."; ?> There are some spelling mistakes and inconsistencies too. I would double-check wherever these requirements came from to see that these weird spellings, inconsistencies, and the missing December are desirable. - December is missing. - agust isn't how you spell august. - setemper isn't how you spell september. - Some of the valid month names are shortened while others aren't. For example, november could be shortened to "nov" to be consistent with "jan". Similar cases go for october.
15th Jul 2020, 1:17 AM
Josh Greig
Josh Greig - avatar
+ 1
$months='month'; not tuesday
15th Jul 2020, 6:39 AM
Maxamed Nuur Maxamuud
Maxamed Nuur Maxamuud - avatar