Array Functions
Advertisements

PHP pos() Function

Topic: PHP Array ReferencePrev|Next

Description

The pos() function returns the value of the current element in an array (alias of current() function).

The following table summarizes the technical details of this function.

Return Value: Returns the value of the current element in an array. Returns FALSE if the array is empty or array's internal pointer points beyond the end of the elements list.
Changelog: Since PHP 7.0.0, array is always passed by value to this function. Prior to this version, it was passed by reference if possible, and by value otherwise.
Version: PHP 4+

Tip: Every array has an internal pointer that points to the current element in the array, when a new array is created, the current pointer is initialized reference the first element in the array. The pos() function does not move the arrays internal pointer in any way.


Syntax

The basic syntax of the pos() function is given with:

pos(array);

The following example shows the pos() function in action.

<?php
// Sample array
$colors = array("red", "green", "blue", "orange", "yellow", "black");

// Getting the current element 
echo pos($colors); // Prints: red
?>

Parameters

The pos() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.

More Examples

Here're some more examples showing how pos() function actually works:

The following example demonstrates how to get the current value from an associative array:

<?php
// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");

// Getting the current element's value
echo pos($alphabets); // Prints: apple

// Getting the current element's key
echo key($alphabets); // Prints: a
?>

The pos() function is commonly used along with the following functions:

  • prev() – Moves the internal pointer of an array to the previous element, and returns its value.
  • next() – Moves the internal pointer of an array to the next element, and returns its value.
  • end() – Moves the internal pointer of an array to its last element, and returns its value.
  • reset() – Set the internal pointer of an array to its first element, and returns its value.
  • key() – Returns the key of the current element in an array.

Here's an example that demonstrates how these functions basically work:

<?php
// Sample array
$colors = array("red", "green", "blue", "orange", "yellow", "black");

// Getting the values 
echo pos($colors);   // Prints: red
echo next($colors);  // Prints: green
echo pos($colors);   // Prints: green
echo end($colors);   // Prints: black
echo pos($colors);   // Prints: black
echo prev($colors);  // Prints: yellow
echo pos($colors);   // Prints: yellow
echo reset($colors); // Prints: red
echo pos($colors);   // Prints: red

// Getting the current element's key
echo key($colors);   // Prints: 0
?>
Advertisements
Bootstrap UI Design Templates