Edit: I meant to ask what is the best/fastest way to get the first match or the first xx matches.
I have an array
$arr = ('abc', 'ded', 'kjld', 'abr', 'cdfd');
I want to shuffle
this array first, and then retrieve ONLY the first value that matches the pattern /ab/
. So, the returned value could be abc or abr.
I looked at preg_grep
, but it will return an array of all the matches. Of course I could just retrieve the first value of the resultant array, but that is wasteful and requires an extra step of array manipulation. Is there another function or a preg_grep
switch that specifies return only the first matched value (or first 5 matched values). I have looked at preg_match
and preg_search
, but they don't seem to give what I want.
You can loop through your array and end the loop when you find a match using break
:
foreach($arr as $value) {
if(preg_match($pattern,$value)) {
$return_string=$value;
break;
}
}
To specify a limit:
$limit=3;
$i=0 // sets the number of returned results to 0
$results=array();
foreach($arr as $value) {
if(preg_match($pattern,$value)) {
// add the result into the array and increment the counter
array_push($results,$value);
$i++;
} if ($i=$limit) break;
}
You can then use another foreach loop to return your values like:
if(count($results)>0)
foreach ($results as $result) {
echo $result;
} else echo "No results found";
Well I believe running preg_grep
and then getting the first value would be fine, but alternatively you could loop your array and return when a match is found like this:
function firstMatch($arr,$pattern) {
foreach($arr as $item) {
if(preg_match($pattern,$item)) {
return $item;
}
}
return 'no match';
}