rob.m
rob.m

Reputation: 10571

how to find the last element in a foreach?

This is what I am trying, using SimpleHtmlDom library

  foreach($html->find('div[class="blogcontent]') as $a) {
    foreach($a->find('p') as $elm) {
      echo $elm->href .$elm->plaintext. '<p>';
      if($elm, -1) {
       return;
      }
    }
  }

I am trying to implement what their doc say:

> // Find lastest anchor, returns element object or null if not found
> (zero based) $ret = $html->find('a', -1); 

But I get:

Parse error: syntax error, unexpected ','

I need to stop the loop and don't echo the last p that it finds

Upvotes: 1

Views: 163

Answers (3)

Eztronics
Eztronics

Reputation: 518

Alternative 1:

You could try to get the last element in the "old way" which is to use count() to get the number of elements then with a counter compare if it is in the last element then if it's true you skipt the last element. This way you can do it:

$a=$html->find('div[class="blogcontent]';
$i = 0;

foreach($a as $as) {
    $b=$as->find('p');
    $total_items = count($b);
    foreach($b as $elm) {
       if ($i == $total_items - 1) {
          return; // or you can use break function to see if it stops on the last element
       }
       echo $elm->href .$elm->plaintext. '<p>';

    }
  }

Alternative 2:

You could use end() to know if you are on the last element this way:

$a=$html->find('div[class="blogcontent]';

foreach($a as $as) {
    $b=$as->find('p');

    foreach($b as $elm) {
       if ($elm === end($b)) {
          return; // or you can use break function to see if it stops on the last element
       }
       echo $elm->href .$elm->plaintext. '<p>';

    }
  }

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212402

Rather than trying to identify the last entry, it might be easier to display the <p> before each entry except for the first

foreach($a->find('p') as $key => $elm) {
    if ($key > 0) {
       echo '<p>';
    }
    echo $elm->href .$elm->plaintext;
}

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57121

If you want to remove the last tag then rather than iterate over all of the data, fetch all values from find() and then remove the last one with array_pop()...

  foreach($html->find('div[class="blogcontent"]') as $a) {
    $pTags = array_pop($a->find('p'));
    foreach( $pTags as $elm) {
      echo $elm->href .$elm->plaintext. '<p>';
    }
  }

If you just want the last <p> tag then

$pTags = $a->find('p');
$lastTag = $pTags[count($pTags)-1];

Upvotes: 1

Related Questions