Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

each() iterates items in reverse order? #9

Open
Black-Platypus opened this issue May 18, 2020 · 1 comment
Open

each() iterates items in reverse order? #9

Black-Platypus opened this issue May 18, 2020 · 1 comment

Comments

@Black-Platypus
Copy link

When I try to use the each() function, I get all the elements in reverse order.
Using the following:

$htmlcode = "<div>
		<ul>
			<li class='dome'>first</li>
			<li class='dome'>second</li>
			<li>third</li>
			<li class='dome'>fourth</li>
			<li>fifth</li>
			<li class='dome'>sixth</li>
		</ul>
	</div>";
$H = new PowerTools\DOM_Query($htmlcode);
$l = $H->select("li.dome");
$l->each(function($i, $el){
	echo($i . ": " . $el);
});

I get:

3:
sixth
2:
fourth
1:
second
0:
first

What's up with that?
I feel like I shouldn't have to write my own wrapper to make this go from top to bottom.
Am I missing something?

@Black-Platypus
Copy link
Author

Huh...
I just had a look at the object, the nodes are actually in the correct order. The each method must be effing something up.
Doing $l->nodes = array_reverse($l->nodes); before the each call gives the correct order.

Yep, for some reason, each is implemented like this:

public function _each($function) {
	$select = $this->select($this->nodes);
	for ($i = count($select->nodes) - 1; $i > -1; $i--) {
		$function($i, $this->select($select->nodes[$i]));
	}
	return $select;
}

where it should be implemented like this:

public function _each($function) {
	$select = $this->select($this->nodes);
	for ($i = 0; $i < count($select->nodes); $i++) {
		$function($i, $this->select($select->nodes[$i]));
	}
	return $select;
}

If this is to ensure smooth sailing even if you remove nodes (thus change the following indices), the better way would be to work on a shadow object, IMO

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant