ZA.
ZA.

Reputation: 10477

How to use in_array() for caseless?

It's a big array, so i won't to strtolower every value.

Upvotes: 1

Views: 332

Answers (3)

Gregor
Gregor

Reputation: 1701

As I know there is only the way with strtolower. See also the comment in the PHP doc: http://ch2.php.net/manual/en/function.in-array.php#88554

Edit: As you can see in the comment, there is of course more than one way to solve it. I probably miss spelled what I tried to say ;-). Sorry.

Upvotes: 0

Gumbo
Gumbo

Reputation: 655219

Try this using the strcasecmp function:

$array = array('foo', 'bar', 'baz', 'quux');
$needle = 'FOO';

$hit = false;
foreach ($array as $elem) {
    if (is_string($elem) && strcasecmp($needle, $elem) == 0) {
        $hit = true;
        break;
    }
}
var_dump($hit);

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545568

Use preg_grep with the case insensitivity flag “i”:

$result = preg_grep('/pattern/i', $array);

Upvotes: 7

Related Questions