Searching Array Using preg_grep()

The preg_grep() function searches all elements of an array, returning an array consisting of all elements matching a certain pattern.

For example, the following function searches an array for foods beginning with p:

$foods = array("pasta", "steak", "fish", "potatoes");
$food = preg_grep("/^p/", $foods);
print_r($food); //  Array ( [0] => pasta [3] => potatoes )

The array corresponds to the indexed order of the input array. If the value at that index position matches, it is included in the corresponding position of the output array. Otherwise, that position is empty.

If you want to remove those instances of the array that are blank, filter the output array through the function array_values() function.

The optional input parameter flags accepts one value, PREG_GREP_INVERT. Passing this flag will result in retrieval of those array elements that do not match the pattern.