user4512402
user4512402

Reputation:

PHP switch/case statement with case-insensitive string comparison

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

Answers (3)

Erdem Olcay
Erdem Olcay

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

Alupotha
Alupotha

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

tnchalise
tnchalise

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

Related Questions