0

I have an array that I am using to display form dropdown options. I would like to be able to display the key of a specified array element.

$options = array(
                    '10' => '10 Results',
                    '15' => '15 Results',
                    '20' => '20 Results',
                    '25' => '25 Results',
                    '30' => '30 Results'
                );

If I use

$selected = '25';
echo $options[$selected]

this of course returns "25 Results". How would I return the key of that element?

key($options)

The above would just return the key of the first element of the array.

4
  • 2
    PHP's array_search function will do that for you. Commented Jul 23, 2013 at 20:00
  • 10
    Isn't $selected the key? Commented Jul 23, 2013 at 20:00
  • @Anthony is right, or you could loop through them yourself with a foreach. key() will return the key for the current index of the array. Commented Jul 23, 2013 at 20:01
  • @hjpotter92 There is so much win in such a short comment. Commented Jul 23, 2013 at 20:02

4 Answers 4

4

Well, since you are defining the key, it's a pretty easy one...

echo $selected;
Sign up to request clarification or add additional context in comments.

1 Comment

+ Smartass, but true :)
2

http://php.net/manual/en/function.array-search.php

In this case, you could use

 $key = array_search('25 Results',$options)

to find the key that matches the value.

Comments

0

One easy way is to use array_flip:

$options = array(
                    '10' => '10 Results',
                    '15' => '15 Results',
                    '20' => '20 Results',
                    '25' => '25 Results',
                    '30' => '30 Results'
                );
$reverseoptions = array_flip($options);

Then just do $reverseoptions['30 Results']; //returns 30;

Limitations exist. You can only do this with a simple array; it cannot be recursive without doing a little more code to make that happen. Also, if any values are alike, the later one will replace the first.

$test = array('1'=>'apple', '2'=>'pear','3'=>'apple');
$testflip = array_flip($test);
print_r($testflip);

//Outputs Array ( [apple] => 3 [pear] => 2 )

I do this often to convert database representations to readable strings.

Comments

0

An alternative to array_search is to use a foreach loop! This is in case you do not know what the key is beforehand.

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}

You can access the keys of the array and do as you wish with them. This will come in handy for doing database conversions as you mentioned.

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.