preg_grep()
preg_grep() — Return array entries that match the pattern.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
Returns the array consisting of the elements of the array array that match the given pattern.
Signature
preg_grep(string $pattern, array $array, int $flags = 0): array|false
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $pattern | string | The pattern to search for, as a string. |
| $array | array | The input array. |
| $flags | int | If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern. |
Return value
Returns an array indexed using the keys from the array array, or false on failure.
Example
A runnable snippet:
$array = [ "4", M_PI, "2.74", 42 ]; // return all array elements containing floating point numbers $fl_array = preg_grep("/^(\d+)?\.\d+$/", $array); var_dump($fl_array);
See also
preg_quote(), preg_match_all(), preg_filter(), preg_last_error()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page preg_grep() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.