how do perform a case insensitive search in an array?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

how do perform a case insensitive search in an array?

Post by jasongr »

Hello

Given the following array:

Code: Select all

$arr = Array('aaa', 'bbb', 'ccc');
Is there an easy way to determine if the string 'AaA' is in the array? Note that I need to perform a case insensitive search, which means that for strings 'AaA', 'AAA', 'aaa' and 'aaA' the answer should be true.
Note that I don't want to modify the array and its values should remain intact

If I check

Code: Select all

$index = array_search('AaA', $arr);
I get $index = false

regards
swdev
Forum Commoner
Posts: 59
Joined: Mon Oct 25, 2004 8:04 am

Post by swdev »

I couldn;t find a built in case-insensitive array match function, but the following code should work.

Code: Select all

<?php

$arr = Array('aaa', 'bbb', 'ccc');
$searchstring = 'cCc';

foreach ($arr as $key => $value)
{
  if (strcasecmp($searchstring, $value) == 0)
  {
    echo 'Found match for ' . $searchstring  . ' at key ' . $key . '<br />';
  }
}

?>
In this example. $key should be 2.

Hope this helps
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

Post by jasongr »

thanks

this is similar to the function that I wrote manually
Post Reply