Looping through an Array without "foreach" in PHP

Q

How To Loop through an Array without Using "foreach" in PHP?

✍: FYIcenter.com

A

PHP offers the following functions to allow you loop through an array without using the "foreach" statement:

  • reset($array) - Moves the array internal pointer to the first value of the array and returns that value.
  • end($array) - Moves the array internal pointer to the last value in the array and returns that value.
  • next($array) - Moves the array internal pointer to the next value in the array and returns that value.
  • prev($array) - Moves the array internal pointer to the previous value in the array and returns that value.
  • current($array) - Returns the value pointed by the array internal pointer.
  • key($array) - Returns the key pointed by the array internal pointer.
  • each($array) - Returns the key and the value pointed by the array internal pointer as an array and moves the pointer to the next value.

Here is a PHP script on how to loop through an array without using "foreach":

<?php
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
print("Loop with each():\n");  
reset($array);
while (list($key, $value) = each($array)) {
  print("[$key] => $value\n");  
}
print("\n");  

print("Loop with current():\n");  
reset($array);
while ($value = current($array)) {
  print("$value\n");  
  next($array);
}
print("\n");  
?>

This script will print:

Loop with each():
[Zero] => PHP
[One] => Perl
[Two] => Java

Loop with current():
PHP
Perl
Java

 

PHP Built-in Functions for Arrays

⇒⇒PHP Tutorials

2017-01-05, 398👍, 0💬