Jump to content

in php array find next index


amolv

Recommended Posts

I found this from php manual under the key() functions comments. This should do it.

 

<?php
    // array_key_relative - Returns a key in an associative array relative to another key without using foreach. Very useful for finding previous key or finding next key in array, etc
    // - Written by Jamon Holmgren (www.jamonholmgren.com). Last revised 8/18/2009. Free for any use.
    // function array_key_relative(array $array, string $current_key, int $offset)
    function array_key_relative($array, $current_key, $offset = 1) {
        // create key map
        $keys = array_keys($array);
        // find current key
        $current_key_index = array_search($current_key, $keys);
        // return desired offset, if in array, or false if not
        if(isset($keys[$current_key_index + $offset])) {
            return $keys[$current_key_index + $offset];
        }
        return false;
    }
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.