12

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?

4
  • 2
    What's your question? Commented Mar 31, 2015 at 23:44
  • 4
    Why do you think a switch statement would be case insensitive? crikey and Crikey aren't the same. Knowing that, work around it and strtoupper or strtolower the values. Alternatively, uppercase the 1st letter of your variable when doing comparisons. Also, why would you want it that way anyway? Commented Mar 31, 2015 at 23:46
  • 1
    He just told you--Force everything to lower case with strtolower($smart), make your case "crickey": and so on and so forth. Commented Mar 31, 2015 at 23:51
  • 1
    Just use a lowercased string to switch and update your cases: eval.in/307176 Commented Mar 31, 2015 at 23:52

3 Answers 3

31

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";
}
?>
Sign up to request clarification or add additional context in comments.

Comments

7

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";
}

?>

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.