How to achieve this: extract key from value?

is there any way to achieve this:

<?php
$my_array 			= array();
$my_array['key1'] 	= 'value1';
$my_array['key2'] 	= 'value2';

function someFunction($input){
	//@todo how to extract key from input
}
?>

usage:
if we use:

someFunction($my_array['key1']);

then inside the function we should be able to extract the key.

I know simple approach is using the way like:

someFunction( array ( 'key1' => 'value1' ));

i would like to extract key from the passed variable like $my_array[‘key1’]

anyway to achieve this?

You would have to pass in the array, or put the array in the global namespace, otherwise you can’t.

function someFunction($array, $value) {
  foreach ($array as $key => $val)
    if ($value == $val) return $key;
  return FALSE;
}

You could probably pull off finding the key for this, using some major hackery by programatically reading the source code.


someFunction($my_array['key1']);

But not stuff like this where the key isn’t a source code litteral.


$key = 'key1';
someFunction($my_array[$key]);
someFunction(current($my_array));

Like dan said, you can fully do it if my_array is a global variable, or you have some other means of the function being able to access the variable scope where that array lives.

[fphp]array_search[/fphp] finds the key for a given value in an array, but you must pass the original array as an argument.

Arguments passed to functions lose their labels in the scope outside the function, there is no way to find out what a variable was called when it was sent to the function - as indeed it may not even be a variable - it could be a constant

foo(‘value’);

Or even the return of another function.

foo(bar(‘value’));

Ok I give up.
I think it is not possible to achieve the way that i mentioned.
anyway thanks for the efforts.