Monday, 2 February 2015

Recursive In Array

Recursive In Array

Here is a function that which functions in the same manner as the PHP in_array() function, except this will search recursively through a multidimensional array. The recursive in_array function takes two parameters and an optional third.
Just like in_array() the function searches $array for any occurrence of $string. If the optional third parameter is set to true, the function will check for type also. Recursively search a multi-dimensional array easily with this.

<?php

    
/**
    *
    * @recursively check if a value is in array
    *
    * @param string $string (needle)
    *
    * @param array $array (haystack)
    *
    * @param bool $type (optional)
    *
    * @return bool
    *
    */
    
function in_array_recursive($string$array$type=false)
    {
        
/*** an recursive iterator object ***/
        
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));

        
/*** traverse the $iterator object ***/
        
while($it->valid())
        {
            
/*** check for a match ***/
            
if( $type === false )
            {
                if( 
$it->current() == $string )
                {
                    return 
true;
                }
            }
            else
            {
                if( 
$it->current() === $string )
                {
                    return 
true;
                }
            }
            
$it->next();
        }
        
/*** if no match is found ***/
        
return false;
    }


    
/*** example usage ***/

    /*** the array to search ***/
    
$array = array(
            array(
'cat''dog''mouse'),
            array(
'dingo''wombat''emu'),
            array(
'fish', array('whale''shark'), 'stingray'),
            
'steve irwin'
            
);
            

    
/*** the string to search for ***/
    
$string 'whale';

    
/*** check if the string is in the array ***/
    
if( in_array_recursive$string$array ) )
    {
        echo 
'found ' $string;
    }
    else
    {
        echo 
$string ' not found.';
    }
?>

0 comments:

Post a Comment