PHP preg_grep Function: Usage, Parameters, Return Value, and Example

This article explains the PHP preg_grep() function, detailing its purpose, parameters, return value, and provides a complete code example that filters an array for floating‑point numbers using a regular expression in PHP scripts.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP preg_grep Function: Usage, Parameters, Return Value, and Example

preg_grep() returns an array of elements from the input array that match the given regular‑expression pattern.

Parameters

pattern : The regex pattern to search for (string).

input : The input array.

flags : Optional flag; if set to PREG_GREP_INVERT, the function returns elements that do not match the pattern.

Return value : An array indexed by the original keys of the input array.

Example 1:

<?php
// Return all elements containing a floating‑point number
$array = array(1, 2, 3.4, 53, 7.9);
$fl_array = preg_grep("/^(
    \d+)?\.\d+$/", $array);
print_r($fl_array);
?>

Output:

Array
(
    [2] => 3.4
    [4] => 7.9
)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendregexphp-functionsarray_filterpreg_grep
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.