1

How to make the value of the array of keys and values in php ? Do it all in one line is not going through an array, and use it for the built-in functions for working with arrays

$array = [
  '0' => 'Amsterdam',
  '1' => 'Berlin',
  '2' => 'Busingen',
];

Result:

$result= [
  'Amsterdam' => 'Amsterdam',
  'Berlin' => 'Berlin',
  'Busingen' => 'Busingen',
];

2 Answers 2

4

You can use array_combine:

array_combine(array_values($array), array_values($array));

Or simply:

array_combine($array, $array);
Sign up to request clarification or add additional context in comments.

2 Comments

good idea with array_combine but I's say it should be just array_combine($array,$array) (OP wants result array to consist of $array's values)
@MarkS @ Ben Fortune Thanks for the note. I've updated the answer
0
function transformArrayKeyValue($array) {    

    $result = array();
    foreach ($array as $key => $value) {
        $result[$value] = $value;
    }

    return $result;
}

Try this code. It should be do what you expected.

Edit : Fixed $key => $value....

1 Comment

Inefficient and doesn't work properly, check $result[$key] = $key; to $result[$value] = $value;

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.