How can one optimize the use of preg_grep in PHP to improve performance when searching for patterns in arrays?

When using preg_grep in PHP to search for patterns in arrays, one way to optimize performance is to compile the regular expression pattern outside of the loop to avoid recompilation on each iteration. This can significantly improve the speed of the search process.

// Compile the regular expression pattern outside of the loop
$pattern = '/^foo/';

// Array to search
$array = ['foo', 'bar', 'foobar', 'baz', 'qux'];

// Use preg_grep with the precompiled pattern
$matches = preg_grep($pattern, $array);

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