Learn PHP Programming

A backend server scripting language, and a powerful tool for making dynamic and interactive Web pages. Learn each topic with examples and output.

PHP Introduction
Control Structures
Php Forms
Php Advanced

PHP Iterables

An iterable is any value which can be looped through with a foreach() loop.

The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function arguments and function return values.

Use an iterable function argument:

    <?php
    function printIterable(iterable $myIterable) {
      foreach($myIterable as $item) {
        echo $item;
      }
    }
    
    $arr = ["a", "b", "c"];
    printIterable($arr);
    ?>
abc

n PHP, the current(), next(), prev(), reset(), and end() functions are used to iterate through arrays. These functions are often used with arrays that have an internal pointer, such as indexed arrays and associative arrays. Here's an overview of each of these functions:

  1. current():

    current($array) returns the current element's value that the internal pointer is pointing to in the array. The internal pointer starts at the first element of the array and moves as you iterate through it or use other array functions.

    If you use current() before any iteration or after reaching the end of the array, it returns false.

    $fruits = ["apple", "banana", "cherry"];
    echo current($fruits); // Output: apple
    
  2. next():

    next($array) moves the internal pointer to the next element in the array and returns its value.

    If you call next() when the internal pointer is already at the end of the array, it returns false.

    $fruits = ["apple", "banana", "cherry"];
    echo next($fruits); // Output: banana    
    
  3. prev():

    prev($array) moves the internal pointer to the previous element in the array and returns its value.

    If you call prev() when the internal pointer is already at the beginning of the array, it returns false.

    echo prev($fruits); // Output: apple      
    $fruits = ["apple", "banana", "cherry"];
    
  4. reset():

    reset($array) moves the internal pointer to the first element of the array and returns its value.

    $fruits = ["apple", "banana", "cherry"];
    echo reset($fruits); // Output: apple
    
  5. end():

    end($array) moves the internal pointer to the last element of the array and returns its value.

    $fruits = ["apple", "banana", "cherry"];
    echo end($fruits); // Output: cherry
    

In next chapter is string Interpolation in php


Share this page on :

=