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?
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 ...
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
}
}
just nest an if in your loop:
foreach($menu_objects as $object){
if($object->chapter == $variable){
// do something here
}
}
Just add an if?
foreach($menu_objects as $object) {
if ($object->chapter == $variable) {
// Do Something?
}
}