0

In PHP, how can I loop only in a part of the multidimensional array ?

For example how to loop into red fruits ?

$fruits = array(
    'red' => array('apple', 'cherry'),
    'yellow' => array('lemon'),
    'orange' => array('orange')
);

Thanks.

2
  • You know how to access an array element, right? You know how to foreach, right? Combine the two. Commented Jan 23, 2018 at 18:08
  • Please add the code you came up with already, as well as your desired output / behavior. Commented Jan 23, 2018 at 18:09

2 Answers 2

1

It's just a normal foreach loop over the inner array. You just need to specify that key rather than iterating the entire $fruits array. Like this:

foreach ($fruits['red'] as $red_fruit) { ...
Sign up to request clarification or add additional context in comments.

Comments

0

Just loop the item you want with foreach:

foreach($fruits['red'] as $fruit) {
   // do something
}

Comments

Your Answer

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