How to check the key of next index of arrays in php?

Member

by jerad , in category: PHP General , 4 months ago

How to check the key of next index of arrays in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 4 months ago

@jerad 

In PHP, you can use the key() function along with next() function to check the key of the next index in an array.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$array = ['apple' => 10, 'orange' => 20, 'banana' => 30];

// Get the current key
$currentKey = key($array);
echo "Current Key: " . $currentKey . PHP_EOL; // Output: apple

// Move the internal pointer to the next element
next($array);

// Get the key of the next index
$nextKey = key($array);
echo "Next Key: " . $nextKey . PHP_EOL; // Output: orange


In this example, the key() function is used to get the current key, and then the next() function is used to move the internal pointer to the next element in the array. Finally, the key() function is used again to get the key of the next index.