Create an assoc array with equal keys and values from a regular array

后端 未结 3 2081
无人共我
无人共我 2020-12-08 18:23

I have an array that looks like

$numbers = array(\'first\', \'second\', \'third\');

I want to have a function that will take this array as

相关标签:
3条回答
  • 2020-12-08 18:30

    You can use the array_combine function, like so:

    $numbers = array('first', 'second', 'third');
    $result = array_combine($numbers, $numbers);
    
    0 讨论(0)
  • 2020-12-08 18:37

    This should do it.

    function toAssoc($array) {
        $new_array = array();
        foreach($array as $value) {
            $new_array[$value] = $value;
        }       
        return $new_array;
    }
    
    0 讨论(0)
  • This simple approach should work:

    $new_array = array();
    foreach($numbers as $n){
      $new_array[$n] = $n;
    }
    

    You can also do something like:

    array_combine(array_values($numbers), array_values($numbers))

    0 讨论(0)
提交回复
热议问题