PHP Iterables – PHP OOP

What is an Iterable in PHP?

A value that can be looped through with a foreach() loop is called a \”iterable.\”

PHP 7.1 added the iterable pseudo-type, which can be used as a data type for function arguments and function return values.

Example

<!DOCTYPE html>
<html>
<body>

<?php
function testIterable():iterable {
return [\”x\”, \”y\”, \”z\”];
}

$varIterable = testIterable();
foreach($varIterable as $item) {
echo $item;
}
?>

</body>
</html>

Output

xyz

PHP: How to Use Iterables

The iterable keyword can be used as an argument data type or as a function\’s return type:

PHP: How to Make Iterables

Arrays

All arrays are iterables, which means that any array can be passed to a function that needs an iterable as an argument.

Iterators

A function that needs an iterable can take as an argument any object that implements the Iterator interface.

An iterator has a list of items and ways to go through them in a loop. It keeps track of a pointer to one of the list\’s items. Each thing on the list should have a key that lets you find it.

This is what an iterator must have:

 

  • current() gives back the element that the pointer is currently pointing to. It can be any kind of data.

     

  • key() gives back the key that goes with the current list item. It can only be a number, a string, a float, or a boolean.

     

  • next() moves the list pointer to the next item.
  • rewind() moves the list pointer to the first item.

     

  • valid() should return false if the internal pointer doesn\’t point to any element. This could happen if next() was called at the end of the list. It comes back true in all other situations
Related Posts
50+ PHP Interview Questions and Answers 2023

1. Differentiate between static and dynamic websites. Static Website The content cannot be modified after the script is executed The Read more

All We Need to Know About PHP Ecommerce Development

  Many e-commerce sites let you search for products, show them off, and sell them online. The flood of money Read more

PHP Custom Web Development: How It Can Be Used, What Its Pros and Cons Are,

PHP is a scripting language that runs on the server. It uses server resources to process outputs. It is a Read more

PHP Tutorial

Hypertext Preprocessor (PHP) is a programming language that lets web developers make dynamic content that works with databases. PHP is Read more

Introduction of PHP

PHP started out as a small open source project that grew as more and more people found out how useful Read more

Syntax Overview of PHP

This chapter will show you some of PHP\'s very basic syntax, which is very important for building a strong PHP Read more

Environment Setup in PHP

To develop and run PHP on your computer, you need to instal three important parts. Web server PHP can almost Read more

Variable Types in PHP

Using a variable is the main way to store information in the middle of a PHP program. Here are the Read more

Scroll to Top