Grant's PHP Tips

In the course of any programmer's journey into PHP, they often need to search the newsgroups and web resources to solve a problem.
The first port of call should always be www.php.net, but there are times when you have trouble finding the answer.
This page is my own personal collection of problems that I couldn't find adequate answers for on the Net.

Matching multiple strings in a PHP switch() statement

I wanted to match multiple strings from an array in a case: statement

	$strings = array($str1,$str2,$str3);
	switch($str_to_match) {
		case $str1:
		case $str2:
		case $str3:
			// do something
			break;
	}
	  

This is OK when you only have a few strings, but gets a bit ugly when your array is large.

On the way to a solution, I tried:

	$strings = array($str1,$str2,$str3);
	switch($str_to_match) {
		case in_array($str_to_match,$strings) :
			// do something
			break;
	}
      

This seems quite dodgy because

in_array($str_to_match,$strings)

just evaluates to TRUE, rather than actually matching the string.

Here is my final solution - if you can think of a better one, please get in touch:

	$strings = array($str1,$str2,$str3);
	switch(TRUE) {
		case ($some_str==$some_other_string) :
			// do something
			break;
		case in_array($some_str,$strings) :
			// do something
			break;
	}
	  

There is an example of this on php.net in the page documenting switch() but I thought this was clearer.

If you want to get in touch, use the contact page