How to get the next value of an array and loop it in the array in PHP

Do you know How to get the next value of an array and loop it in the array in PHP ?

To achieve the desired behavior where you want to get the next value from the array given the last value (and wrap around to the first value if the last value is the last element of the array), you can create a PHP function. Here’s a simple implementation for such a function:

function getNextValue(array $values, $lastValue) {
    $lastIndex = array_search($lastValue, $values);
    $nextIndex = ($lastIndex + 1) % count($values);
    return $values[$nextIndex];
}

You can use this function as follows:



$values = [1, 2, 5, 4, 8];
$lastValue = 8;
$nextValue = getNextValue($values, $lastValue);
echo $nextValue; // Output: 1

 

The function takes an array of values and the last value you have. It then finds the index of the last value in the array using array_search. Next, it calculates the index of the next value by adding 1 to the last index and using the modulus (%) operator to ensure that it wraps around to the first index when needed. Finally, it returns the next value based on the calculated index.

Post Your Questions on our forum

Post a question on Forum

Ajith Jojo Joseph

Self taught, dedicated young entrepreneur with many licensed products under his sleeve. Passionate about technology, business and excellence in general.

Share with your friends:

Comments are closed.

How to get the next value of an array and loop it in the array in PHP

Do you know How to get the next value of an array and loop it in the array in PHP […]

July 28, 2023

New Open Source CRM for project Management and Invoicing

I’m excited to announce the launch of my new open source project: Gmax CRM. an invoicing and project management tool […]

December 31, 2022

Post View Counts WordPress plugin (Documentation)

The Post View Counts plugin is a simple tool for tracking and displaying the number of views for each post […]

December 30, 2022

How to create Laravel Flash Messages

Laravel flash messages are a convenient way to display one-time notifications to the user after a form submission or other […]

December 22, 2022

Digital Marketing Toolkit

Get Free Access to Digital Marketing Toolkit. You can use all our tools without any limits

Get Free Access Now