Home »
PHP
PHP prev() function with example
PHP prev() function: Here, we are going to learn about the prev() function with example in PHP.
Submitted by IncludeHelp, on February 26, 2019
PHP prev() function
prev() function firstly moves the current pointer to the previous element and returns the element.
Syntax:
prev(array);
Note: As we have discussed in last two posts (current() function in PHP and next() function in PHP) that an array has a pointer that points to the first element by default, next() function can be used to move the pointer to next element and then to print it and similarly a prev() function can be used to move the pointer to previous element and print it.
Examples:
Input:
$arr1 = array(10, 20, 30, 40, 50);
Function call:
current($arr1);
next($arr1);
prev($arr1);
Output:
10
20
10
Input:
$arr2 = array("name" => "Amit", "age" => 21, "Gender" => "Male");
Function call:
current($arr2);
next($arr2);
prev($arr2);
Output:
Amit
21
Amit
PHP code:
<?php
$arr1 = array(10, 20, 30, 40, 50);
$arr2 = array("name" => "Amit", "age" => 21, "Gender" => "Male");
echo current($arr1) . "\n"; //print first element
echo next($arr1) . "\n"; //move to next element and print
echo prev($arr1) . "\n"; //move to previous element and print
echo current($arr2) . "\n"; //print first element
echo next($arr2) . "\n"; //move to next element and print
echo prev($arr2) . "\n"; //move to previous element and print
?>
Output
10
20
10
Amit
21
Amit
TOP Interview Coding Problems/Challenges