Financial Calculator

Calculate loans, SIP, PPF, NPS & more!

Financial Calculator

Calculate loans, SIP, PPF, NPS & more!

PHP lterables

PHP
l

PHP Iterables

PHP में Iterable एक ऐसा data type है जिसे loop किया जा सकता है। Iterable का उपयोग foreach के साथ किया जाता है। यह array और ऐसे objects को represent करता है जो loop होने योग्य हों।

  • Iterable में arrays और Traversable interface को implement करने वाले objects आते हैं।
  • Function या method parameter को iterable type-hint देकर हम ensure करते हैं कि उसे केवल iterable values ही मिलें।
  • Iterable को foreach लूप के साथ directly iterate किया जा सकता है।

Iterable Type Hinting

हम किसी function parameter के लिए iterable type-hint दे सकते हैं ताकि वह केवल iterable values (array या traversable object) ही स्वीकार करे।

उदाहरण: Iterable Type Hint
<?php
function printValues(iterable $items) {
   foreach ($items as $value) {
     echo $value . "<br>";
   }
}

$arr = ["Apple", "Banana", "Mango"];
printValues($arr);
?>
Output
Apple
Banana
Mango

Iterable Return Type

हम किसी function को iterable return करने के लिए भी declare कर सकते हैं।

उदाहरण: Iterable Return Type
<?php
function getFruits(): iterable {
   return ["Apple", "Orange"];
}

foreach (getFruits() as $fruit) {
   echo $fruit . "<br>";
}
?>
Output
Apple
Orange

Iterable with Objects

अगर कोई class IteratorAggregate या Iterator interface को implement करती है, तो उसके objects भी iterable बन जाते हैं।

उदाहरण: Iterable Using IteratorAggregate
<?php
class Fruits implements IteratorAggregate {
   private $list = ["Apple", "Kiwi", "Grapes"];

   public function getIterator() {
     return new ArrayIterator($this->list);
   }
}

$fruits = new Fruits();
foreach ($fruits as $fruit) {
   echo $fruit . "<br>";
}
?>
Output
Apple
Kiwi
Grapes
Article By: Brajlal Prasad
Created on: 03 Nov 2025  5  Views
 Print Article
Report Error

If you want to report an error, or any suggestion please send us an email to [email protected]

Financial Calculator

Financial Calculator

Take control of your finances with our powerful Financial Calculator app—calculate loans, SIP, PPF, NPS and more all in one place!

Play Store