1

Is it possible to get the array key name this way?

$array = ("first" => 1);

function f($object)
{
echo(???); //should give first
}

f($array['first']);
1
  • what do you want to get? Commented Feb 7, 2012 at 10:15

3 Answers 3

2

It's not possible if you pass only the value into the function like f($object['first']), the key name has no relation to the passed value in that case.

You need to pass the entire array (f($array)) and use:

echo key($object);
Sign up to request clarification or add additional context in comments.

Comments

0

I don't really know what you want to get, but I guess this will help you:

$array = array('foo' => 'bar', 'baz' => 'foobar');

foreach ($array as $key => $value) {
  echo $key . ' = ' . $value . '<br />';
}

This will return

foo = bar
baz = foobar

Comments

0

I would use

$array = ("first" => 1);

function f($object, $key) {
    echo($key); // will give first
    echo($object[$key]); // will give 1
}

f($array, 'first');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.