Sebastian Sebastian - 3 months ago 6
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

Thanks.

Answer

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

    $oldArray['dyna[0]']='a';
    $oldArray['zzzzzzzzzzzzzz']='b';
    $oldArray['dyna[1]']='c';
    $oldArray['zzzzzzzzzzzz']='d';

print_r($oldArray);


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

print_r($newArray);

//output:

Array
(
    [dyna[0]] => a
    [zzzzzzzzzzzzzz] => b
    [dyna[1]] => c
    [zzzzzzzzzzzz] => d
)
Array
(
    [dyna[0]] => a
    [dyna[1]] => c
)
Comments