0

I have an array of objects I'm using to create a menu, and each object has the properties id, video_id and chapter_id.

I'd like to make a for each loop such as

foreach($menu_objects as $object WHERE $object->chapter == $variable)

Is there a way of doing this?

2
  • paste some sample data of $menu_objects Commented Nov 13, 2012 at 13:43
  • Probably easiest just to have a if test inside the foreach. Commented Nov 13, 2012 at 13:43

4 Answers 4

4

PHP doesn't offer syntax like that, however, you could always make it an if-statement as the first line in the loop:

foreach ($menu_objects as $object) {
    if ($object->chapter != $variable) continue;
    ... process as normal ...
Sign up to request clarification or add additional context in comments.

2 Comments

+1, I like this style best because it reduces nesting and it makes immediately clear to the developer that items like that will not be processed (you don't have to read to the end of the if block to see that).
By far the best solution. Simple and fast.
1

just nest an if in your loop:

foreach($menu_objects as $object){
  if($object->chapter == $variable){
    // do something here
  }
}

Comments

0

Few ways

foreach(array_filter($menu_objects, function($o) { return $o->chapter == $variable}) as $object)

Or

foreach($menu_objects as $o)
{
    if ($o->chapter == $variable)
    {
        //Code here
    }
}

Comments

0

Just add an if?

foreach($menu_objects as $object) {
   if ($object->chapter == $variable) {
      // 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.