Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
array
communitycreator

What is the prev() method in PHP?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The prev method is used to move the position of the internal pointer of the array one step backward and return the value.

In PHP, each array contains an internal pointer that points to the current element. It initially points to the first element of the array. We can move the pointer positions using methods like next, prev, etc.

Syntax

prev(array|object &$array): mixed

If an array is empty or if the position pointed by the internal pointer is before the first element of the array, then false is returned.

Example

<?php
$numbers = [1,2,3];
// 3
echo "Last value is : ". end($numbers). "\n";
//2
echo "Previous value is : ". prev($numbers). "\n";
//1
echo "Previous value is : ". prev($numbers). "\n";
// pointer now points before first element
echo "Previous Value is : ";
var_dump(prev($numbers));
?>

In the code above:

  • We created a numbers array.

  • We moved the internal pointer to the last element of the array using the end method and printed the value.

  • We used the prev method to move the pointer position one step backward and printed the value pointed by the pointer.

RELATED TAGS

php
array
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring