rfc:array_key_first_last_index
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revisionNext revisionBoth sides next revision | ||
rfc:array_key_first_last_index [2015/12/07 17:07] – created jbafford | rfc:array_key_first_last_index [2016/01/01 20:11] – jbafford | ||
---|---|---|---|
Line 19: | Line 19: | ||
array_key_last() returns the last key in an array. | array_key_last() returns the last key in an array. | ||
- | array_key_index() returns the key at a specified index (using a substr-like offset; | + | array_key_index() returns the key at a specified index (using a substr-like offset; |
- | All three functions return the requested array key, or null if the requested array key is not found (an empty array, or an out-of-bounds index in the case of array_key_index). | + | <code php> |
+ | $arr [' | ||
+ | |||
+ | $key = array_key_first($arr); | ||
+ | |||
+ | $key = array_key_last($arr, | ||
+ | |||
+ | $key = array_key_index($arr, | ||
+ | $key = array_key_index($arr, | ||
+ | $key = array_key_index($arr, | ||
+ | |||
+ | |||
+ | // Also works for numeric arrays | ||
+ | $numeric = [1 => 1, 5 => 2, 2 => 3]; | ||
+ | $key = array_key_index($numeric, | ||
+ | $key = array_key_index($numeric, | ||
+ | $key = array_key_index($numeric, | ||
+ | </ | ||
+ | |||
+ | |||
+ | All three functions return the requested array key, or null if the requested array key is not found (an empty array, or an out-of-bounds index in the case of array_key_index). | ||
Line 35: | Line 55: | ||
* Retrieving the last key can be done by either of these more complicated/ | * Retrieving the last key can be done by either of these more complicated/ | ||
* foreach(array_reverse($arr) as $key => $value) { break; } | * foreach(array_reverse($arr) as $key => $value) { break; } | ||
- | * foreach($arr as $key => $value); //Iterate over the entire array; as a possibly unexpected | + | * foreach($arr as $key => $value); //Iterate over the entire array, doing nothing, just for the side-effect |
* reset($arr); | * reset($arr); |
rfc/array_key_first_last_index.txt · Last modified: 2017/09/22 13:28 by 127.0.0.1