0

i have this array

Array
(
  [0] => a
  [1] => b
  [2] => c
  [3] => d
)

how can i get an element's key?(for example a=0,c=2)

6 Answers 6

4
<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>

http://www.php.net/manual/en/function.array-flip.php

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

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>
Sign up to request clarification or add additional context in comments.

Comments

3

Use array_search()

Searches the array for a given value and returns the corresponding key if successful.

Example #1 array_search() example

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

1 Comment

You should be nominated for the 'Quickest answer' in the world :)
0

If you want to search, see array_search (http://www.php.net/manual/en/function.array-search.php)

If you are iterating over it, you can use various syntax:

foreach ($a as $key => $value) { ... }
foreach (array_keys($a) as $key) { $value = $a[$key]; ... }

Comments

0

If you just want the keys use array_keys.

If you want to flip the array like you show in your example, use array_flip

Comments

0

array_keys:

array_keys($arr, 'a');         # 0
array_keys($arr, 'c');         # 2

Comments

0

I personally like @SilentGhost's solution but you would suffer a speed penalty if you are doing more than one search, at which point you would want the following:

// assume you know you want the value for key 'c'
$array = ('a','b','c','d');
$keys = array_flip($array);
return $keys['c'];

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.