0

Lets say I have an array with a structure like this:

$arr= Array(
    array(
    "id"=>"a"
    "type">"apple"),

    array(
    "id"=>"b"),

    array(
    "id"=>"c"),

    array(
    "id"=>"c"
    "type"=>"banana")
);

now I want to have a foreach loop which fetches all the array elements which have a key in them named "type".

Something like

foreach(all arrays which have type in them as $item)

How would I do that?

many thanks.

2 Answers 2

2

Try this:

 foreach ($arr as $key => $value)
   if (array_key_exists("type", $value))
     var_dump($value);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Is there anyway I can get the required elements without having to traverse the entire array?
1
foreach($arr as $arrsub)
{
    if(isset($arrsub['type']))
    {
       //here do your stuff
    }
}

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.