1

Following on this SO question regarding array brackets

I would like to know if it is possible / how to print the array index i.e. I would like to display the values which is in single quotes 'expensive', 'meduim' etc

$cars   = array ('expensive' => $BMW,
                 'medium'    => $Volvo,
                 'cheap'     => $Lada);
1
  • 2
    use array_keys to get keys of an array Commented Feb 22, 2017 at 4:45

2 Answers 2

0
$cars = array (
    'expensive' => $BMW,
    'medium'    => $Volvo,
    'cheap'     => $Lada
);

foreach (array_keys($cars) as $index) {
    echo "$index<br/>\n";
}
Sign up to request clarification or add additional context in comments.

Comments

0

How do you plan on accessing $BMW, $Volvo, or $Lada without the key name?

If you know the value of $BMW you could perform array_search() [http://php.net/manual/en/function.array-search.php] on the array.This will return the first key found with a matching value.

array_keys() [http://php.net/manual/en/function.array-search.php] returns an array of the keys.

key()[http://php.net/manual/en/function.key.php] returns the key at a given array element.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.