Monday, 2 February 2015

Substr In Array

Substr In Array

To find if a value exists in an array, the PHP in_array() function works quite nicely. But there are times when only a partial match is required to check in the array. This substr_in_array() function checks will search the values of an array for a substring. The $needl can be a string or an array of strings to search for.

<?php
/**
 *
 * @Search for substring in an array
 *
 * @param string $neele
 *
 * @param mixed $haystack
 *
 * @return bool
 *
 */
function substr_in_array($needle$haystack)
{
    
/*** cast to array ***/
    
$needle = (array) $needle;

    
/*** map with preg_quote ***/
    
$needle array_map('preg_quote'$needle);

    
/*** loop of the array to get the search pattern ***/
    
foreach ($needle as $pattern)
    {
        if (
count(preg_grep("/$pattern/"$haystack)) > 0)
        return 
true;
    }
    
/*** if it is not found ***/
    
return false;
}
?>

EXAMPLE USAGE


<?php
/*** an arrray to search through ***/$array = array('dingo''wombat''kangaroo''platypus');
/*** an array of values to search for ***/$strings = array('foo''bar''kang');
/*** check for true or false with ternary ***/echo  substr_in_array$strings$array ) ? 'found' 'not found';
/*** a single string to search for ***/$string 'plat';
/***  check for true or false with ternary ***/echo substr_in_array$string$array ) ? 'found' 'not found';?>

0 comments:

Post a Comment