S
S
Sergey Semenko2016-02-24 16:13:55
PHP
Sergey Semenko, 2016-02-24 16:13:55

PHP. What is the magic?

Good afternoon,
I've encountered a small problem today. I managed to solve it, but I didn’t understand one thing:
In short, here is a working piece of code

foreach ($this->allowableTags as $tag) {
      foreach ($doc->getElementsByTagName($tag) as $element) {
        $attributes = $element->attributes;
        $attrs = [];
        for ($i = 0; $i < $attributes->length; ++$i) {
          $attrs[] = $attributes->item($i);
        }
        foreach ($attrs as $attr) {
          $this->clearElement($element, $attr);
        }
      }
    }

And here is the non-working
foreach ($this->allowableTags as $tag) {
      foreach ($doc->getElementsByTagName($tag) as $element) {
        $attributes = $element->attributes;
        for ($i = 0; $i < $attributes->length; ++$i) {
          $attr = $attributes->item($i);
          $this->clearElement($element, $attr);
        }
      }
    }

In fact, there is no difference, but in the first example all attributes are removed, but not in the second. Why is that? And what other solutions are there?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2016-02-24
@abler98

Because when an attribute is removed, the rest are renumbered. Let there be three attributes, their numbers will be 0, 1 and 2.

Шаг 1. 
  $i = 0. 
  Удаляем атрибут 0.
  Атрибуты 1 и 2 получают номера 0 и 1.
Шаг 2.
  $i = 1.
  Удаляем атрибут 1.
  Остался атрибут 0.

Well, PHP is not at all to blame here.
foreach ($this->allowableTags as $tag) {
  foreach ($doc->getElementsByTagName($tag) as $element) {
    $attributes = $element->attributes;
    while ($attributes->length > 0) {
      $attr = $attributes->item(0);
      $this->clearElement($element, $attr);
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question