How to convert an array of arrays or objects to an associative array?

I had the exact same problem some days ago. It is not possible using array_map, but array_reduce does the trick.

$arr = array('a','b','c','d');
$assoc_arr = array_reduce($arr, function ($result, $item) {
    $result[$item] = (($item == 'a') || ($item == 'c')) ? 'yes' : 'no';
    return $result;
}, array());
var_dump($assoc_arr);

result:

array(4) { ["a"]=> string(3) "yes" ["b"]=> string(2) "no" ["c"]=> string(3) "yes" ["d"]=> string(2) "no" }


As far as I know, it is completely impossible in one expression, so you may as well use a foreach loop, à la

$new_hash = array();

foreach($original_array as $item) {
    $new_hash[$item] = 'something';
}

If you need it in one expression, go ahead and make a function:

function array_map_keys($callback, $array) {
    $result = array();

    foreach($array as $item) {
        $r = $callback($item);

        $result[$r[0]] = $r[1];
    }

    return $result;
}

Tags:

Php

Array Map