PHP Iterables

PHP - What is an Iterable?


An iterable is any value that can be looped through with a foreach loop.


In PHP, an iterable can be:

  • An array
  • An object that implements the Traversable interface (like generators or iterators)


The iterable pseudo-type was introduced in PHP 7.1.


PHP - Using Iterables


The iterablepseudo-type can be used in function arguments and return types to indicate that the value must be something you can iterate over using foreach.

Example
<?php
function loopItems(iterable $items) {
foreach ($items as $item) {
echo $item . "<br>";
}
}
$data = ['apple', 'banana', 'cherry'];
loopItems($data);
?>

Try it yourself

You can also return an iterable:

Example
<?php
function getColors(): iterable {
return ['red', 'green', 'blue'];
}
foreach (getColors() as $color) {
echo $color . "<br>";
}
?>

Try it yourself

PHP - Creating Iterables


1. Arrays Are Iterables


All arrays in PHP are inherently iterable and can be passed to functions expecting an iterable type.


2. Iterators Are Also Iterables


Any object that implements the Iterator interface is considered iterable. This allows for custom iteration logic.


The Required Methods of the Iterator Interface


To be a valid iterator in PHP, your class must implement:

Method

Purpose

current()

Returns the value of the current item

key()

Returns the key of the current item (int, float, bool, or string)

next()

Moves the pointer to the next item

rewind()

Resets the pointer to the first item

valid()

Returns true if the current position is valid, otherwise false

Example
<?php
class MyIterator implements Iterator {
private $items = ["a" => "Apple", "b" => "Banana", "c" => "Cherry"];
private $keys = [];
private $index = 0;
public function __construct() {
$this->keys = array_keys($this->items);
}
public function current() {
return $this->items[$this->keys[$this->index]];
}
public function key() {
return $this->keys[$this->index];
}
public function next() {
$this->index++;
}
public function rewind() {
$this->index = 0;
}
public function valid() {
return isset($this->keys[$this->index]);
}
}
// Use the custom iterator
$iterator = new MyIterator();
foreach ($iterator as $key => $value) {
echo "$key => $value<br>";
}
?>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.