Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - PHP Built-in Functions for Arrays

By: FYICenter.com

Part:   1  2  3  4  5   6  7 

(Continued from previous part...)

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

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

How To Create an Array with a Sequence of Integers or Characters?

The quickest way to create an array with a sequence of integers or characters is to use the range() function. It returns an array with values starting with the first integer or character, and ending with the second integer or character. Here is a PHP script on how to use range():

<?php
print("Integers:\n");
$integers = range(1, 20, 3);
print_r($integers);
print("\n");

print("Characters:\n");
$characters = range("X", "c");
print_r($characters);
print("\n");
?>

This script will print:

Integers:
Array
(
    [0] => 1
    [1] => 4
    [2] => 7
    [3] => 10
    [4] => 13
    [5] => 16
    [6] => 19
)

Characters:
Array
(
    [0] => X
    [1] => Y
    [2] => Z
    [3] => [
    [4] => \
    [5] => ]
    [6] => ^
    [7] => _
    [8] => `
    [9] => a
    [10] => b
    [11] => c
)

Of course, you can create an array with a sequence of integers or characters using a loop. But range() is much easier and quicker to use.

(Continued on next part...)

Part:   1  2  3  4  5   6  7 


Selected Developer Jobs:

More...