1

Is it possible to have an AND in a foreach loop?

For Example,

foreach ($bookmarks_latest as $bookmark AND $tags_latest as $tags)
ritch
  • 1,760
  • 14
  • 37
  • 65
  • I don't see what kind of situation would call for this. But you can't do it. What are you trying to do? – Rob Jun 12 '11 at 18:50
  • Refer to this other question: http://stackoverflow.com/questions/6313340/codeigniter-passing-arguments-from-view-to-controller – ritch Jun 12 '11 at 18:53

6 Answers6

4

You can always use a loop counter to access the same index in the second array as you are accessing in the foreach loop (i hope that makes sense).

For example:-

$i = 0;
foreach($bookmarks_latest as $bookmark){
   $result['bookmark'] = $bookmark;
   $result['tag'] = $tags_latest[$i];
   $i++;
}

That should achieve what you are trying to do, otherwise use the approach sugested by dark_charlie.

In PHP 5 >= 5.3 you can use MultipleIterator.

vascowhite
  • 18,120
  • 9
  • 61
  • 77
1

Short answer: no. You can always put the bookmarks and tags into one array and iterate over it.

Or you could also do this:

reset($bookmarks_latest);
reset($tags_latest);
while ((list(, $bookmark) = each($bookmarks_latest)) && (list(,$tag) = each($tags_latest)) {
    // Your code here that uses $bookmark and $tag
}

EDIT:
The requested example for the one-array solution:

class BookmarkWithTag  {
  public var $bookmark;
  public var $tag;
}

// Use the class, fill instances to the array $tagsAndBookmarks


foreach ($tagsAndBookmarks as $bookmarkWithTag)  {
  $tag = $bookmarkWithTag->tag;
  $bookmark = $bookmarkWithTag->bookmark;
}
Karel Petranek
  • 15,005
  • 4
  • 44
  • 68
0

you can't do that.

but you can

<?php
foreach($keyval as $key => $val) {
  // something with $key and $val
}

the above example works really well if you have a hash type array but if you have nested values in the array I recommend you:

or option 2

<?php
foreach ($keyval as $kv) {
 list($val1, $val2, $valn) = $kv;
}
Gabriel Sosa
  • 7,897
  • 4
  • 38
  • 48
0

No, but there are many ways to do this, e.g:

reset($tags_latest);
foreach ($bookmarks_latest as $bookmark){
    $tags = current($tags_latest); next($tags_latest);
    // here you can use $bookmark and $tags
}
Floern
  • 33,559
  • 24
  • 104
  • 119
0

No. No, it is not.

You'll have to manually write out a loop that uses indexes or internal pointers to traverse both arrays at the same time.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

Yes, for completeness:

foreach (array_combine($bookmarks_latest, $tags_latest) as $bookm=>$tag)

That would be the native way to get what you want. But it only works if both input arrays have the exact same length, obviously.

(Using a separate iteration key is the more common approach however.)

mario
  • 144,265
  • 20
  • 237
  • 291