user391986
user391986

Reputation: 30896

Convert array of keys to associative array

I have an array of data like so

[
 'one', 'two', 'three'
]

I need to convert it like so

[
  'one' => 'one',
  'two' => 'two'
]

I found out about array_flip which gives me

[
   'one' => 0,
   'two' => 0,
   'three' => 0
]

What can I do from there? Any clean PHP way to do this?

Upvotes: 4

Views: 734

Answers (4)

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17576

use array_combine()

array_combine — Creates an array by using one array for keys and another for its values

$a = array('one', 'two', 'three');
$a = array_combine($a, $a);

Upvotes: 5

Thi Tran
Thi Tran

Reputation: 701

Try this code

<?php
     $arr = array('one', 'two', 'three');
     $result = array();
     foreach ($arr as $value) {
         $result[$value] = $value;
     }
     print_r($result);
?>

Upvotes: 0

John Conde
John Conde

Reputation: 219804

Just use array_combine() with the same array used for the keys and the values:

$array = [
 'one', 'two', 'three'
];

$new_array = array_combine($array , $array);

Demo

Upvotes: 2

mike.k
mike.k

Reputation: 3437

array_combine() is the way to go

$a = array('one', 'two', 'three');
$output = array_combine($a, $a);

Upvotes: 8

Related Questions