xchampionx
xchampionx

Reputation: 106

Count results inside foreach then store that value in a variable to be used elsewhere

How do you count the results inside a foreach then store that value in a variable to be used on another foreach.

Example. This foreach returns 5 items

foreach ($xml->items as $item) {
  echo "$item->name";
  echo "$item->address"; 
}

Now I want that the foreach above be counted and stored in say $totalitems and be used on another foreach. This second foreach also counts its results and store in $totalitems2. Something like this:

foreach ($xml->items as $item) { //Same source but they will be displayed separately based on a condition.
  echo "$item->name";
  echo "$item->address";
  if_blah_blah_meet_condition_then_break;
}

So basically what I want here is to restrict the total number of items being displayed on both foreach combined. $totalitems and $totalitems2 should have the sum of 8. 8 is the number I want limit the items returned. Doesn't matter if the other foreach has more items than the other. 3 and 5. 4 and 4. 6 and 2. Etc.

How can I achieve this? Please advice.

Upvotes: 0

Views: 1449

Answers (4)

Alvaro
Alvaro

Reputation: 41595

It seems your array is stored in xml->items therefor, you only would have to save it in another variable if you want to store it.

foreach ($xml->items as $cont=>$item) {
  echo "$item->name";
  echo "$item->address"; 

  if($cont<8){
      $totalItems_one[] = $item; 
  }
}

//whatever changes you do to $xml->items

foreach ($xml->items as $cont=>$item) {
  echo "$item->name";
  echo "$item->address"; 

  if($cont<8){
      $totalItems_two[] = $item; 
  }
}

Like this you have the two new arrays totalItems_one and totalItems_two and you can get the number of items just doing count($totalItems_one) or count($totalItems_two) whenever you want.

Upvotes: 0

Teena Thomas
Teena Thomas

Reputation: 5239

Just use count($xml->items) and that value in the condition, inside the loop.

Upvotes: 0

Damien Overeem
Damien Overeem

Reputation: 4529

$totalItems = count($xml->items);
foreach ($xml->items as $item) {
  echo "$item->name";
  echo "$item->address"; 
}

Upvotes: 1

Joseph at SwiftOtter
Joseph at SwiftOtter

Reputation: 4321

Just use the simple iterator ++ methods. When you are on the second foreach, watch for when $i passes the number that you want to stop it.

Code:

$i = 0;    
foreach ($xml->items as $item) {
    echo "$item->name";
    echo "$item->address";
    $i++;
}

foreach ($xml->items as $item) {
    echo "$item->name";
    echo "$item->address";

    $i++;
    if ($i > 5) { // or whatever the number is
        break;
    }
}

Upvotes: 3

Related Questions