note 92999 deleted from function.key by googleguy

From: Date: Tue, 22 Oct 2013 06:48:16 +0000
Subject: note 92999 deleted from function.key by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-196650@lists.php.net to get a copy of this message
Note Submitter: jamon at clearsightdesign dot com ---- I wrote a simple, yet powerful function for finding a key in an array relative to another key. This is very useful for finding the next key in an associative array if you know the current key, or any other arbitrary key relative to the current key. This function does not use a foreach loop. I have not tested it for speed compared to a foreach loop. I would assume it's faster since it uses PHP's built in functions, but I could be wrong. I'd appreciate feedback on this. - Jamon Holmgren <?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; } ?> Usage example: <?php $test_array = array( "apple" => "Red, shiny fruit", "orange" => "Orange, dull, juicy fruit", "pear" => "Usually green and odd-shaped fruit", "banana" => "Long yellow fruit that monkeys like to eat", "cantelope" => "Larger than a grapefruit", "grapefruit" => "Kind of sour" ); echo array_key_relative($test_array, "apple", 2); // outputs "pear" echo array_key_relative($test_array, "orange", -1); // outputs "apple" */ $next_key = array_key_relative($test_array, "banana", 1); // Get the key after banana (cantelope) echo $test_array[$next_key]; // outputs "Larger than a grapefruit" ?>

« previous php.notes (#196650) next »