Is there a better/elegant way of setting array keys to related values?

Let's say, I've got an array that looks like this:

Array
(
    [0] => red
    [1] => green
    [2] => blue
)

I want the keys of this array to be the same as the related values. So the result should look like this:

Array
(
    [red] => red
    [green] => green
    [blue] => blue
)

The values of the initial array will be unique, so this is not an issue.

To get the result, I would normally use a foreach loop:

$aResult = array();
foreach($aColors as $sValue)
{
  $aResult[$sValue] = $sValue;
}

My the question is: Is there a better/elegant way of doing this ?

Edit: Many of you want to know why I need an array like this. So I'll explain. I'm using a framework, which generates a select box for me. The function uses array keys and values to apply them to the select options like so:

<select>
  <option value="red">red</option>
  <option value="green">green</option>
  <option value="blue">blue</option>
</select>

In this case the keys would match the values.

Answers


$aResult = array_combine($aColours, $aColours);

But its pretty pointless to do so because it doesn't give you anything that your original array doesn't already give you.

EDIT

You may also find the following variants useful:

$aColours = array('red','orange','yellow','green','blue','indigo','violet');

$aResult = array_combine(
    $aColours,
    array_map(
        'ucfirst',
        $aColours
    )
);

var_dump($aResult);

uses the lower-case values defined in your initial array for the keys, but generates upper-case first letter for the display values

$aColours = array('Red','Orange','Yellow','Green','Blue','Indigo','Violet');

$aResult = array_combine(
    array_map(
        'strtolower',
        $aColours
    ),
    $aColours
);

var_dump($aResult);

Uses mixed-case display values defined in your initial array for the values, but generates lower-case for the keys


Need Your Help

How to push json into a nested array - angularjs

c# asp.net angularjs

I can make it work when hardcoding the data, like this:

Change command Method for Tkinter Button in Python

python user-interface tkinter

I create a new Button object but did not specify the command option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.