John Davidson

php - Does Iterator work only with numeric arrays?

0 comments
Message:


I saw an example at w3schools:


<?php
// Create an Iterator
class MyIterator implements Iterator {
private $items = [];
private $pointer = 0;

public function __construct($items) {
// array_values() makes sure that the keys are numbers
$this->items = array_values($items);
}

public function current() {
return $this->items[$this->pointer];
}

public function key() {
return $this->pointer;
}

public function next() {
$this->pointer++;
}

public function rewind() {
$this->pointer = 0;
}

public function valid() {
// count() indicates how many items are in the list
return $this->pointer < count($this->items);
}
}

// A function that uses iterables
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}

// Use the iterator as an iterable
$iterator = new MyIterator(["a", "b", "c"]);
printIterable($iterator);
?>

Can current method loop the arrays if it a associative array and not numeric.If yes how can i do it ? Example can we do something like this :


function printIterable(iterable $myIterable) {
foreach($myIterable as $item => $value) {
echo "$item - $value";
}
}

// Use the iterator as an iterable
$iterator = new MyIterator(["a"=>1, "b"=>2, "c"=>3]);
printIterable($iterator);

When i try it. It print this : 0 - 11 - 22 - 3



My Answer:
No, the Iterator interface in PHP can work with any type of data structure, not just numeric arrays. It allows you to iterate over objects that implement the Iterator interface, which can be used to traverse through elements in a custom data structure.

The example you saw at w3schools may have used a numeric array for simplicity, but the Iterator interface can be implemented in a variety of ways to work with different types of data structures.

Rate this post

5 of 5 based on 5045 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us