Sebastian Sebastian - 1 year ago 52
PHP Question

Only keep elements with a certain name pattern in an associative php array and remove the remaining elements from the array

I have an associative Php array, which looks like this on print_r

Array ( [dyna[0]] => one [add[0]] => ⇊ [rem[0]] => Delete Column [dyna[1]] => two [add[1]] => ⇊ [rem[1]] => Delete Column [dyna[2]] => three [add[2]] => ⇊ [rem[2]] => Delete Column [dyna[3]] => four [add[3]] => ⇊ [rem[3]] => Delete Column [input[1]] => numbers [store_last] => 6 )

Ask : I would like to only keep elements in the array that have the key -> dyna[0] , dyna[1] and remove the remaining keys an values which have keys like like e.g add[0] and rem[1].

Is it possible to do that? please suggest


Answer Source

array_filter allows for easy array filtering based on a user function:



$newArray = array_filter(
    function ($key) {
         return preg_match('/^dyna\[\d+\]/', $key); //regular expression to match key name



    [dyna[0]] => a
    [zzzzzzzzzzzzzz] => b
    [dyna[1]] => c
    [zzzzzzzzzzzz] => d
    [dyna[0]] => a
    [dyna[1]] => c
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download