Wednesday, March 3, 2010

PHP 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';
?>

2 Comentários:

MLM Software said...

Hey. like as tutor.

Pooja

MLM Developers India

http://mlmdevelopers.com/products/mlm-software/corporate-mlm-soft/feature.html

Prince Brown said...

ARIES TECH SOFT PVT LTD provides you with the best MLM(MULTI LEVEL MARKETING) software in binary as well as matrix form.MLM Software is very important and critical to your business success. MLM Software which is really a life line of any MLM company. MLM companies are running on trust. Without online software, it's really difficult to run your MLM Company. So before deciding for online software for your company, you need to examine the brief history of company.



mlm software Delhi

Post a Comment

Latest Comments

About Me

My photo
Makassar, Sulawesi Selatan, Indonesia

Guest Book


ShoutMix chat widget

Script Sense ©Template Blogger Green by Dicas Blogger.

TOPO