ShoeLace1291
ShoeLace1291

Reputation: 4698

How do I return the key of a certain value in an array?

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.

Upvotes: 0

Views: 78

Answers (4)

Kirk Backus
Kirk Backus

Reputation: 4866

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.

Upvotes: 0

DevlshOne
DevlshOne

Reputation: 8457

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

echo $selected;

Upvotes: 4

Bil1
Bil1

Reputation: 438

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.

Upvotes: 0

Sir Pakington Esq
Sir Pakington Esq

Reputation: 583

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.

Upvotes: 2

Related Questions