0

I am having trouble on adding a counter starting from 1 to the following piece of code, near echo $images; I would like to count how many times it echoes $images. My purpose i to add the number next to images. Any help would be great! Please have in mind if there is a way of making the following code better. Thank you!

foreach($items as $item) {
    $descr = $xPath->query('./description', $item);

    foreach ($descr as $d) {

        $temp_dom = new DOMDocument();
        $temp_dom->loadHTML( $d->nodeValue );
        $temp_xpath = new DOMXPath($temp_dom);
        $img = $temp_xpath->query('//div[@class="separator"]//img');

 foreach ($img as $imgs) {   
$images=$imgs->getAttribute('src'); 
echo $images; }

   }

}
3
  • what do you want your counter to count? Commented Mar 26, 2011 at 17:19
  • I would like to count how many times it echoes $images. My purpose i to add the number next to images. Commented Mar 26, 2011 at 17:21
  • This is not about XPath expressions. Commented Mar 26, 2011 at 23:12

3 Answers 3

1

Initialize a variable, e.g. $count = 0;, and then add 1 on each loop:

 foreach ($img as $imgs) {   
$images=$imgs->getAttribute('src'); 
++$count; // <= here you go
echo $images; }
Sign up to request clarification or add additional context in comments.

Comments

0

foreach don't maintain its own counter, if you want a counter you can use the for loop instead

for ($i = 0; $i <= count($img).; $i++) {
    $images = $img[i]->getAttribute('src');
    echo $images;
}

Or you can just initialize your own counter in the foreach

foreach($img as $imgs) {
$i = 1;
$images = $imgs->getAttribute('src');
echo $images;
$i++;
}

Comments

0

Can't you just add something like

$counter = 0;

before the firsrt foreach, and then somethin like

$counter++;
echo $images;
echo $counter;

just increase counter at same time, you echo $images. Or am I missing 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.