note 92999 added to function.key
| From: | jamon at clearsightdesign dot com | Date: | Wed, 19 Aug 2009 05:24:40 +0000 |
| Subject: | note 92999 added to function.key | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-159622@lists.php.net to get a copy of this message | ||
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"
?>
----
Server IP: 64.71.164.2
Probable Submitter: 71.216.201.233
----
Manual Page -- http://www.php.net/manual/en/function.key.php
Edit -- https://master.php.net/note/edit/92999
Del: integrated -- https://master.php.net/note/delete/92999/integrated
Del: useless -- https://master.php.net/note/delete/92999/useless
Del: bad code -- https://master.php.net/note/delete/92999/bad+code
Del: spam -- https://master.php.net/note/delete/92999/spam
Del: non-english -- https://master.php.net/note/delete/92999/non-english
Del: in docs -- https://master.php.net/note/delete/92999/in+docs
Del: other reasons-- https://master.php.net/note/delete/92999
Reject -- https://master.php.net/note/reject/92999
Search -- https://master.php.net/manage/user-notes.php