in_array() and multidimensional array

前端 未结 22 1653
眼角桃花
眼角桃花 2020-11-22 00:30

I use in_array() to check whether a value exists in an array like below,

$a = array(\"Mac\", \"NT\", \"Irix\", \"Linux\");
if (in_array(\"Irix\"         


        
22条回答
  •  遇见更好的自我
    2020-11-22 01:15

    I was looking for a function that would let me search for both strings and arrays (as needle) in the array (haystack), so I added to the answer by @jwueller.

    Here's my code:

    /**
     * Recursive in_array function
     * Searches recursively for needle in an array (haystack).
     * Works with both strings and arrays as needle.
     * Both needle's and haystack's keys are ignored, only values are compared.
     * Note: if needle is an array, all values in needle have to be found for it to
     * return true. If one value is not found, false is returned.
     * @param  mixed   $needle   The array or string to be found
     * @param  array   $haystack The array to be searched in
     * @param  boolean $strict   Use strict value & type validation (===) or just value
     * @return boolean           True if in array, false if not.
     */
    function in_array_r($needle, $haystack, $strict = false) {
         // array wrapper
        if (is_array($needle)) {
            foreach ($needle as $value) {
                if (in_array_r($value, $haystack, $strict) == false) {
                    // an array value was not found, stop search, return false
                    return false;
                }
            }
            // if the code reaches this point, all values in array have been found
            return true;
        }
    
        // string handling
        foreach ($haystack as $item) {
            if (($strict ? $item === $needle : $item == $needle)
                || (is_array($item) && in_array_r($needle, $item, $strict))) {
                return true;
            }
        }
        return false;
    }
    

提交回复
热议问题