1

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.

Sebastian
  • 89
  • 2
  • 12

1 Answers1

1

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
)
  • most likely a botched name attribute in the actual form – Kevin Aug 17 '16 at 00:47
  • yeah i really dont think this is best, but still waiting to here back from the OP –  Aug 17 '16 at 00:49
  • @Dagon yes the square bracket is intentionally there, my validation works on that, I am getting this data from a form dynamically, i wouldn't know how many dyna[] elements the form has, hence i will be running a loop for the count, but before running the loop i have to eliminate all other keys and values but dyna[] keys and values – Sebastian Aug 17 '16 at 01:10
  • ok let me rewrite the answer based on the new information, give me a few minutes –  Aug 17 '16 at 01:13
  • @Sebastian new answer added –  Aug 17 '16 at 01:30
  • @Dagon , Fantastic ! just curious , is there a way to achieve the same without using preg_match regular expressions – Sebastian Aug 17 '16 at 01:37
  • strpos would work but you want be able to match `dyna[(anynuber)]` with it you would have to just match `dyna` which is why i choose it –  Aug 17 '16 at 01:39
  • @Dagon , I am trying this same suggestion you gave me now at my home computer and it throwing an error, at home i think i have php 5.6 err - Use of undefined constant ARRAY_FILTER_USE_KEY - assumed 'ARRAY_FILTER_USE_KEY , do you know whats going on ? – Sebastian Aug 17 '16 at 05:51
  • Changelog ¶ Version Description 5.6.0 Added optional flag parameter and constants ARRAY_FILTER_USE_KEY and ARRAY_FILTER_USE_BOTH –  Aug 17 '16 at 05:59