Sunday 9 June 2013

USING POINTERS FOR ARRAYS IN PHP

For using pointers in arrays in php we basically use three functions:-

  1. current()
  2. next()
  3. reset()
The first two functions returns an element of array.

/******************************************************************************/
<html>
<head>
<title>Pointers for Arrays</title>
</head>
<body>
<?php
$arr=array(11,12,13,14,15,16,17,18,19,20);

/* for printing the first element of the array */
echo current($arr)."<br />";

echo next($arr)."<br />";
echo next($arr)."<br />";
/* for shifting the pointer to next element */
echo next($arr)."<br />";
echo next($arr)."<br />";

echo current($arr)."<br />";

/* for resetting the position to its first element */
reset($arr);

echo "after resetting = ".current($arr)."<br />";

?>
</body>
</html>
/******************************************************************************/
Output:-
11
12
13
14
15
15
after resetting = 11

Here the current($arr), whenever invoked will point to that array element where the pointer is set to. Note that initially the pointer will be pointing the first element of the array, and the next($arr) will be pointing to the next element of the array. The reset() function will reset the array pointer in such a way that the array pointer will again point to the starting element of the array.

No comments:

Post a Comment