Search code examples
phparraysassociativeindexed

Indexed/numerical array to an associative array with PHP


Is there anyway that an indexed array say ['1' => 'dave, '2' => 'ryan', '3' => 'mike', '4' => 'sam'] can be turned into an associative array. Which in this case would be ['dave' => 'ryan', 'mike' => 'sam'].

Obviously in the context and with the example i've given it doesn't make much sense but it would be helpful would just be handy to know.

All I can find on Google or here is ways of doing the opposite (associative -> indexed) unless I am completely missing an obvious answer.


Solution

  • This is the simplest way that I can think of for your example:

    $arr = array('1' => 'dave', '2' => 'ryan', '3' => 'mike', '4' => 'sam');
    $result = array();
    $key = null;
    
    foreach(array_keys($arr) as $k) {
        $v = $arr[$k];
    
        if($key === null) {
            $key = $v;
        } else {
            $result[$key] = $v;
            $key = null;
        }
    }
    

    Here's a demo.