1

I have an array defined:

$flatdata["body_font-family"] = "Arial";

I want to use that array value in a function:

function display_name($input) {
    showmethekeyofthearrayvalue($input); // how can I get the key name here?
}

echo display_name($flatdata["body_font-family"]);

So that the output is:

body_font-family

3 Answers 3

2

You may try like this:

key($arr);

This will return the key name

From the manual

key() returns the index element of the current array position.

Or you may try to use array_search

$arr = array ('key1' => 'a', 'key2' => 'b', );
$key = array_search ('a', $arr);
Sign up to request clarification or add additional context in comments.

Comments

0

What about this?

function display_key($array, $val) {
    while($array_pos = current($array)) {
        if($array_pos == $val) {
            return key($array);
        }
    }
}

echo display_key($flatdata, $flatdata["body_font-family"]);

4 Comments

PHP Warning: key() expects parameter 1 to be array, string given
Same problem as before.
Works perfect now, didn't think there would be a solution. Thanks!
No problem :) I accidently returned key($val) instead of key($array) firstly
0

I'm assuming displaykey is supposed to be display_name in your example.

If so, you won't be able to return the key by passing in an array element such as $flatdata["body_font-family"] because in this case you're only passing in a specific string i.e. Arial, so the function doesn't have any info about the key.

2 Comments

You're probably correct. I thought there was some kind of PHP function I didn't know, but alas.
@Taapo another way to think of it is that the call in your example is the equivalent of display_name('Arial')

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.