1

Let's say I have an array that looks like this:

$array[0] = 'House';
$array[1] = 'Condo';
$array[2] = 'Townhouse';
$array[3] = 'Land';

If I passed a var which contains either "condo" or "Condo" (in other words, case-insensitive), I want to return 1, indicating that $array[1] matches "condo" or "Condo" or "CONDO".

So basically I want:

$search = 'Condo';
$key = get_property_key($search, $array);
// $key should return 1

Is there a quick PHP method to do this? Or do I need to write my own function to loop through? If it's the latter, you don't need to write out the function for me - I can handle it myself. But I'm hoping there's a PHP function that I missed during my "education" period (although this education period NEVER ends).

1

5 Answers 5

8

There's no built-in for case-insensitive search, but this works, based on plain old array_search()

 array_search(strtolower($search),array_map('strtolower',$array)); 
Sign up to request clarification or add additional context in comments.

Comments

3

You can use array_search, though that's case sensitive. For an non-case sensitive array_search, you could do something like this:

function get_property_key($needle, $haystack){
    return array_search(strtolower($needle), array_map('strtolower', $haystack));
}

1 Comment

Yup Michael beat you by a minute.. same thing really. Gave you +1 anyway thanks so much, you guys rock.
0

What about something like this

    foreach($array as $i){
        if(strtolower($i) == strtolower($query)){
            //do something
            return;
        }
    }

3 Comments

That would search the value, not the key. If you had $a=>$i in the foreach line this may work. However the above solutions with array_key() function was the more elegant & simpler solution.
@jeffkee but arent you searching for the value.. i.e. Condo.. and not the key?
No, as the question clearly states, I need the $key: "$key should return 1"
-1

There's no built in function; you'd have to roll your own. I'm not sure if this will suit your needs but on approach about be to index the array with the lower cased version and then look for $array[strtolower($search))]

1 Comment

apparently array_search() is a function.
-1

Why not populate the array with key names for the value you are searching, normalized so it's always lowercase :

$array['condo'] = true;
$array['land']  = true;
//and so on

//and then the search becomes really fast
if (isset($array[strtolower($search)])) {
  //element found
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.