I have the following function
function blah($string) {
$match = array('red', 'green', 'blue');
$replace = array('1', '1,', '0');
return str_replace($match, $replace $string);
}
What I'm trying to do is, if the input is not in the match array, re开发者_运维问答turn 0.
Since this is only used on the back end once/day, performance isn't the biggest issue but since i'm still learning PHP, I'd like to understand the proper way of doing this.
Any help is really appreciated! Thanks in advance!
I suggest using PHP's built-in in_array()
function instead of writing your own.
How about:
function blah($string) {
$matches = array('red', 'green');
return in_array($string, $matches);
}
Another thing I might add is that you should avoid using a function like str_replace
(which, at a glance, would mean replacing strings) for something that is testing existence as it might confuse other programmers (or yourself) when reading the code.
I ended up using the following code:
function approved($input) {
$match = array('red','green','blue');
if(in_array(strtolower($input), $match)) {
return 1;
} else {
return 0;
}
}
精彩评论