0

Below is a simple array that I created:

$colors = array(

"parent1" =>array(
    "item1"=>"red", 
    "item2"=>"green", 
    "item3"=>"blue", 
    "item4"=>"yellow"   
),

"parent2" =>array(
    "item1"=>"red", 
    "item2"=>"green", 
    "item3"=>"blue", 
    "item4"=>"yellow"   
)   

); 

What I need to get is the key of my level 1 arrays which are string "parent1" and "parent2".

Currently I'm using foreach with while loop to get the key

foreach ($colors as $valuep) {
    while (list($key, $value) = each($colors)) {
        echo "$key<br />";
    }
}

but I'm only able to get the "parent2" string from using the above method and not "parent1".

3 Answers 3

1

You're so close.

foreah($colors as $key => $val)
{
   echo $key . "<br/>";
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use the key like so:

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

Comments

1

To print out the keys:

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

You can also get all of the keys from an array by using the array_keys() method, for example:

$keys = array_keys($colors);

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

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.