phparrayskeyexplodetext-parsing

Access the key of a flat array and parse the delimited key string into an array


I have an array like

Array
(
    [select_value_2_1] =>  7
)

I want to explode index into Array ([0]=select_value, [1]=2, [2]=1)


Solution

  • You can't just use explode() because it will also separate select from value. You could alter your output so that instead you have array keys like selectValue_2_1.

    Then you can do what you want:

    $items = array('selectValue_2_1' => 1);
    
    foreach ($items as $key => $value) {
        $parts = explode('_', $key);
    }
    

    That will yield, for example:

    array('selectValue', '2', '1');
    

    You can use array_keys() to extract the keys from an array.