phparraysfilterkeyassociative-array

Filter a flat associative array to keep elements with keys which start with a specified word


I`m using $_POST array with results of checkbox's selected from a form.

I'm thinking of using php in_array function but how could I extract only values that start with chk Given the following array:

Array ( 
    [chk0] => 23934567622639616 
    [chk3] => 23934567622639618 
    [chk4] => 23934567622639619 
    [select-all] => on 
    [process] => Process
)

Solution

  • Simple and fast

    $result=array();
    foreach($_POST as $key => $value){
    
        if(substr($key, 0, 2) == 'chk'){
             $result[$key] = $value;
        }
    }