Comparing and finding matched elements from an array

Often it comes to requirement when we need to compare and return matched set of values from an array.


Suppose we have an array like


WE want to find images that start with images/im and videos that starts with videos/vi then we can use preg_grep which is used to compare array elements with regular expression defined and returns match array elements, The code will be like:

$matchedFiles = preg_grep('/^(images\/im)|(videos\/vi)/', $array); //get objects that start with images/im OR videos/vi OR audios/au from all objects         
        $matchedFiles = array_filter(array_values($matchedFiles));
        echo "<br>Matched elemets are:";