How can the preg_grep function be effectively used in PHP to search for a pattern in an array?

The preg_grep function in PHP can be effectively used to search for a pattern in an array by providing a regular expression pattern and an array to search within. The function will return an array containing elements from the input array that match the specified pattern.

// Define the array to search within
$array = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

// Define the regular expression pattern to search for
$pattern = '/^b/';

// Use preg_grep to search for elements starting with 'b' in the array
$matches = preg_grep($pattern, $array);

// Output the matched elements
print_r($matches);