PHP / case output using case insensitive string comparison

Comparing strings in the / case chain 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"; } ?> 

โ€œAlt Andetโ€ prints above the code, but I would like to compare case-insensitive strings and print โ€œCrikeyโ€. How can i do this?

+5
source share
3 answers

Converting input to upper or lower case, the problem is resolved.

 <?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"; } ?> 
+16
source

Use the stristr() function for case statements. stristr() is case strstr() and returns the entire haystack, from the first appearance of the 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"; } ?> 
+7
source

if you use lowercase inputs, you can convert them to the uppercase first character of each word in a string

ucwords - fill in 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"; } ?> 

useful links from doc:

first character of each word
Make the string of the first character in uppercase
Make a lowercase line
Make a string in uppercase

+2
source

Source: https://habr.com/ru/post/1216573/


All Articles