1

Is there a function for creating an associative array with the values of the original array as both key and value? I already looked at array_flip and array_keys but they don't seem to be able to create this.

Say i have this array:

[0 => 'foo', 1 => 'bar']

And i want to convert this to:

[foo => 'foo', bar => 'bar']

Obviously this would work, but i'm looking for a function.

$array = [];
foreach ($original_Arr as $key => $value) {$choices[$value] = $value;}
Jonas de Herdt
  • 422
  • 5
  • 18
  • `array_combine(array_values($arr), array_values($arr))` – Alon Eitan Jan 05 '21 at 16:42
  • As the array is a plain array, you can miss out the `array_values()` part and use `array_combine($arr, $arr)` – Nigel Ren Jan 05 '21 at 16:48
  • @NigelRen Actually the documentation _Creates an array by using the **values** from the keys array as keys and the **values** from the values array as the corresponding values._ So it will actually work also with an associative array and not just plain one – Alon Eitan Jan 05 '21 at 16:51

1 Answers1

0
  1. Use array_combine to create the result.

array_combine ( array $keys , array $values ) : array

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Pass your original array as both the keys and values to create the desired outcome

<?php
    
    $array = [];
    $array[0] = 'foo';
    $array[1] = 'bar';
    
    $res = array_combine($array, $array);
    print_r($res);
Array
(
    [foo] => foo
    [bar] => bar
)

Try it online!


The above solution does not work when applying multidimensional arrays.

You'll need to 'flatten' the array before passing to array_combine to get the desired values;

<?php
    
    $array = [];
    $array[] = 'foo';
    $array[1] = 'bar';
    $array[2] = [ 'foobar', 'barfoo' ];
    
    $values = flat($array);
    
    $res = array_combine($values, $values);
    print_r($res);
    
    function flat($array) {
        $values = [];
        array_walk_recursive($array, function($a) use (&$values) { $values[] = $a; });
        return $values;
    }
Array
(
    [foo] => foo
    [bar] => bar
    [foobar] => foobar
    [barfoo] => barfoo
)
0stone0
  • 34,288
  • 4
  • 39
  • 64