I didn’t know PHP did that!

Last modified date

Comment: 1

For the number of years that I’ve been using PHP (and let’s just say that I know people working in PHP roles today that weren’t alive when I started using it!), I would have thought I’d know a lot of the ins and outs of the language… But I’m very happy to say that it’s still surprising me to this day.

Why am I happy about that? Because I get to learn new things.

And it’s the small things that really put a smile on my face. Yes, sure, it’s all nice and lovely to learn a new design pattern or some theoretical (often opinionated) way that an application should be designed. But when I find there’s a handy little function or parameter that I never knew existed…?

Yes, I’m a simple man that enjoys simple pleasures in life. 🙂

And with that all said, let me introduce to you the first post (of what I’m sure will be many) because I didn’t know PHP did that!

preg_grep

Have you ever found yourself wanting to iterate through an array of values to see if there’s a partial match of a value?

You may have found yourself doing something along the lines of:

<?php

$drinks = ['apple', 'pear', 'blackcurrant and apple'];

$matched = [];
foreach ($drinks as $drink) {
    if (stristr($drink, 'apple')) {
        $matched[] = $drink;
    }
}

or with any variation around that. However, I didn’t know that PHP had the preg_grep function – must have totally over looked that one!

This function will take your array and return anything that matches your given regular expression.

So the above could be re-written as the far more succinct:

<?php

$drinks = ['apple', 'pear', 'blackcurrant and apple'];
$matched = preg_grep('/apple/i', $drinks);

In addition, the preg_grep function has a flags third parameter where if you supply PREG_GREP_INVERT it will return elements that don’t match your regex instead of ones that do.

Share

1 Response

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.