Reputation:
Switch/case string comparison is case-sensitive.
<?php
$smart = "crikey";
switch ($smart) {
case "Crikey":
echo "Crikey";
break;
case "Hund":
echo "Hund";
break;
case "Kat":
echo "Kat";
break;
default:
echo "Alt Andet";
}
?>
Above code prints "Alt Andet", but I would like to compare strings case-insensitively and print "Crikey". How can I do that?
Upvotes: 12
Views: 15606
Reputation: 427
Use stristr()
function on case statements. stristr()
is case-insensitive strstr()
and returns all of haystack starting from and including the first occurrence of needle to the end.
<?php
$smart = "crikey";
switch ($smart) {
case stristr($smart, "Crikey"):
echo "Crikey";
break;
case stristr($smart, "Hund"):
echo "Hund";
break;
case stristr($smart, "Kat"):
echo "Kat";
break;
default:
echo "Alt Andet";
}
?>
Upvotes: 7
Reputation: 10093
if you use lower case inputs then you can convert them to capitalized first character of each word in a string
ucwords — Uppercase the first character of each word in a string
<?php
$smart = "crikey";
switch (ucwords($smart)) {
case "Crikey":
echo "Crikey";
break;
case "Hund":
echo "Hund";
break;
case "Kat":
echo "Kat";
break;
default:
echo "Alt Andet";
}
?>
helpful links from doc:
first character of each word
Make a string's first character uppercase
Make a string lowercase
Make a string uppercase
Upvotes: 2
Reputation: 1583
Convert the input to either uppercase or lowercase, problem solved.
<?php
$smart = "cRikEy";
switch (strtolower($smart)) {
case "crikey": // Note the lowercase chars
echo "Crikey";
break;
case "hund":
echo "Hund";
break;
case "kat":
echo "Kat";
break;
default:
echo "Alt Andet";
}
?>
Upvotes: 31