PHP Array only get those elements/values whose keys match a particular pattern

115 views Asked by At

I have a multi-dimensional & nested array like below:

Array
(
    [_edit_lock] => Array
        (
            [0] => 1504299434:6
        )

    [_edit_last] => Array
        (
            [0] => 6
        )
    [additional_photos_0_gallery_image_1] => Array
        (
            [0] => 77556
        )
    [additional_photos_0_gallery_image_2] => Array
        (
            [0] => 77567
        )
    [additional_photos_0_gallery_image_3] => Array
        (
            [0] => 73768
        )
    ....
)

Now I need to get only those elements of the given array(in a separate array without changing current array), whose keys match a particular pattern like below:

additional_photos_[any_number]_gallery_image_[any_number]

How can I get using one of the array functions and avoiding foreach loops ?

1

There are 1 answers

0
Philipp On BEST ANSWER

Just use array_filter and preg_match.

return array_filter($data, function($key) {
    return preg_match('~^additional_photos_[0-9]+_gallery_image_[0-9]+$~', $key);
}, ARRAY_FILTER_USE_KEY);