note 71445 deleted from function.in-array by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: RQuadling at GMail dot com 

----

In trying to emulate a case insensitive in_array(), I came up with ...

<?php
function in_array_caseless($m_Needle, array $a_Haystack, $b_Strict = False)
    {
    // Let's assume the function will fail.
    $b_Result = False;

    // Compare array vs array
    if (is_array($m_Needle))
        {
        // Iterate the Haystack to compare each Bale with the Needle.
        foreach($a_Haystack as $a_Bale)
            {
            // Determine the intersection between the Needle and the Bale.
            // Strictness indicates that the associative indexes must also match using case insensitivity.
            if (
                ($b_Strict && (array_uintersect_uassoc($m_Needle, $a_Bale, 'strcasecmp', 'strcasecmp') === $m_Needle)) ||
                (!$b_Strict && (array_uintersect($m_Needle, $a_Bale, 'strcasecmp') === $m_Needle))
                )
                {
                // It it matches then we have a winner.
                $b_Result = True;

                // Don't process anything else as 1 match is all that is required.
                break;
                }
            }
        }

    // Compare everything else but reverse the Haystack and the Needle.
    // This is done as the return from array_uinterect is based upon its Needle
    // and we need the Haystack's type to compare for strictness.
    else
        {
        $a_Result = array_values(array_uintersect($a_Haystack, array($m_Needle), 'strcasecmp'));
        $b_Result = !$b_Strict || (gettype($m_Needle) == gettype($a_Result[0]));
        }

    // Return the result
    return $b_Result;
    }
?>

For more info on this and other cool functions please see http://rquadling.php1h.com.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.