0

I have an array like this

array(
0 => "bar",
1 => "foo",
);

and I want output like this

array(
"bar" => "bar",
"foo" => "foo",
);

how can i achieve this?

3 Answers 3

7

Assuming your original array is strictly a numeric array:

Actually works for non-numeric as well:

array_combine($array, $array);

http://codepad.org/fxOmIh2D

1
$arr = array(
0 => "bar",
1 => "foo",
);

$arrCombine = array_combine($arr, $arr);

print_r($arrCombine);
gives

Array
(
    [bar] => bar
    [foo] => foo
)
1

in case non numeric array

simple logic of using value as key works

$array1 = array(
   0 => "bar",
   "cat" => "foo",);
foreach($array1 as $key => $value)
{
    $array1[$value] = $value;
    unset($array1[$key]);
}

var_dump($array1);

gives

array(2) {
  ["bar"]=>
  string(3) "bar"
  ["foo"]=>
  string(3) "foo"
}

and if its strict use answer above, would be faster i guess and clean code too.

http://codepad.org/x3Z1zLjz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.