1
Array
(
    [0] => '1 Fail'
    [1] => '2 Fail'
    [2] => '3 Pass'
    [3] => '4 Pass'
    [4] => '5 Pass'
)

Array
(
    ['1 Fail'] => '1 Fail'
    ['2 Fail'] => '2 Fail'
    ['3 Pass'] => '3 Pass'
    ['4 Pass'] => '4 Pass'
    ['5 Pass'] => '5 Pass'
)

Is there a php function to convert from array 1 to array 2

PS: I know this so i am looking for a built in function

foreach($result as $value)
{
    $assoc[$value] = $value;
}
5
  • You can swap keys and values, but I don't think there's a built-in function to copy values to their respective keys. Commented Dec 15, 2011 at 12:07
  • what's wrong with "this"? Why can't you browse array functions list yourself? Commented Dec 15, 2011 at 12:09
  • I won't think there is anything shorter than the four lines you already have. Commented Dec 15, 2011 at 12:09
  • nothings wrong but is there a way just for knowledge Commented Dec 15, 2011 at 12:10
  • This is a valid question., +1 PHP has built-ins for most any low-level array operation you could imagine. It's not at all unreasonable to expect there would be one for this, and to ask. Commented Dec 15, 2011 at 12:11

3 Answers 3

5

Assuming all your array values are unique:

$assoc = array_combine(array_values($arr), array_values($arr));
Sign up to request clarification or add additional context in comments.

1 Comment

how different is ur approach from in terms of speed from @DaveRandom
1

You could:

array_walk($array, function ($value, &$key) {
  $key = $value;
});

...but a more pertinent point is: why do you need to do this?

It seems like this is a very odd requirement, and whatever you need to do would be better done some other way...

2 Comments

how different is ur approach from in terms of speed from @codaddict
Unknown - probably depends very much on environment, PHP version and server configuration. It is unlikely to make any practical difference though, unless your array is ridiculously big. Premature optimisation is the root of all evil, apparently (although personally, I suspect Micro$oft)
1

You can use array_combine

$arr    = array(
'1 fail',
'2 fail',
'3 fail',
'4 fail',
);
print_r(array_combine($arr, $arr));



Array
(
    [1 fail] => 1 fail
    [2 fail] => 2 fail
    [3 fail] => 3 fail
    [4 fail] => 4 fail
)

Comments

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.