How to tell if the keys is defined in an array?

What I’m trying to do: Make a generic way to output <select> lists given an array.

Say there are three arrays:


     $r1 = array('Hello','World');
     $r2 = array('Bar'=>'Foo','Hello'=>'World');
     $r3 = array(0=>'First',1=>'Second');

What I want $r1 to do is, set the keys such that if it’s not explicitly defined - to use it’s value as the key. So that I can output:


    <select name='foo'>
        <option value='Hello'>Hello</option>
        <option value='World'>World</option>
    </select>

While the others will set it’s value attribute according to what’s defined.

Any ideas?

$r1 = array_flip($r1);

What your asking for is impossible, as when you assign the array like this:

$r1 = array('Hello','World');

PHP will assign “Hello” to the key 0 and “World” to the key 1.

With other words they will have keys assigned to them.

This means that as long as you allow integer keys to be counted as “assigned” keys, there is no way to differentiate if it was a key you set yourself, or if it was auto assigned.

In the event that you do only count string keys as assigned ones, then you can easily just check the key to see if it is a string or integer and if its an integer to use the value for key.

yeah that’s the conclusion I was at, was just wondering if there’s some method PHP has, in the unlikely event that it in fact keeps track of who defined the integer index.

The easiest way to make this work, is most probably to assign the value as a key when you initiate the array if possible.

I.e. that if you dont have a key set, you use the value as a key right there, instead of trying to find out later on.

Why not just store an array of arrays?


<?php
$options = array(
    array('foo'),
    array(1, 'bar')
);

You then just have to count how many items are in the array.


<?php
$options = array(
	array('foo'),
	array(1, 'bar')
);


foreach($options as $option)
{
	if(1 === count($option))
	{
		$key = $value = $option[0];
	}
	else
	{
		list($key, $value) = $option;
	}
	echo "<option value=\\"{$key}\\">{$value}</option>", PHP_EOL;
}


/*
	<option value="foo">foo</option>
	<option value="1">bar</option>
*/

Anthony.

That option would be more resource demanding than to set them from the start, since that would also require you to know if the key exists or not.

A more resource friendly option would be something like this.

function prepareArray(&$options, $value, $key=null) {
	$options[(($key === null)?$value:$key)] = $value;
	}

$options = array();

//When you assign the values you have you just do, if you are uncertain that there is a key or not
prepareArray($options, $array_value, ((empty($array_key))?null:$array_key));

//Or if your certain that the value has no key
prepareArray($options, $array_value);

//Or if your certain it has a key
prepareArray($options, $array_value, $array_key);