phparraysvalidationcase-insensitive

How to implement a case-insensitive version of in_array()?


I have this code here:

if (in_array('mystring', $entry->getCategories()->getValues()))
{
   ... //do somethingA

This works.

However, I want to allow somethingA to run, if mystring OR mYstring or MYSTRING is this case.

So I've tried like so:

if (in_array(array('OCC', 'OCc','Occ', 'occ', 'ocC','oCC', 'oCc', 'OcC'), $entry->getCategories()->getValues()))
{

But I get nothing returned. What am I missing here?


Solution

  • in_array() cannot compare the values of two arrays, nor can it compare strings case-insensitively. From the manual:

    If needle is a string, the comparison is done in a case-sensitive manner.

    You can try this trick instead. Map strtolower() to the categories array so everything is in lowercase, then search the array for the lowercase string:

    $cats_lower = array_map('strtolower', $entry->getCategories()->getValues());
    
    if (in_array('mystring', $cats_lower))
    {
        // Do something
    }