note 95210 added to language.types.array
| From: | john at nowhere dot com | Date: | Fri, 18 Dec 2009 17:33:26 +0000 |
| Subject: | note 95210 added to language.types.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-164117@lists.php.net to get a copy of this message | ||
If you ever wondered if you can do something like:
<?php
$a = function_that_returns_an_array()['some_index']['some_other_index'] ;
?>
The answer is no, you can't. But you can use the following function. I named it i() because
it's a short name and stands for "to index".
<?php
/**
* Usage: i( $array, $index [, $index2, $index3 ...] )
*
* This is functionally equivalent to $array[$index1][$index2][$index3]...
*
* It can replace the more prolix
*
* $tmp = some_function_that_returns_an_array() ;
* $value = $tmp['some_index']['some_other_index'] ;
*
* by doing the job with a single line of code as in
*
* $value = i( some_function_that_returns_an_array(), 'some_index',
'some_other_index' ) ;
*
* Note that since this function is slower than direct indexing, it should only be used in cases
like the one
* described above, for improving legibility.
*
* @param $array
* @param $index
* @param [optional] $index2, index3, ...
* @throws Exception when the indexes do not exist
*/
function i(){
$args = func_get_args();
$array = $args[0];//gets the fist parameter, $array
$indexes = $args;
unset($indexes[0]);//because indexes[0] is actually not an index, but the first parameter, $array
foreach( $indexes as $index ){
if( (! is_array($array)) || (! array_key_exists( $index, $array )) ){
throw new Exception("Array index out of bounds. Parameters:".print_r($args,true));
}
$array = $array[$index];
}
return $array;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 187.20.125.35
----
Manual Page -- http://www.php.net/manual/en/language.types.array.php
Edit -- https://master.php.net/note/edit/95210
Del: integrated -- https://master.php.net/note/delete/95210/integrated
Del: useless -- https://master.php.net/note/delete/95210/useless
Del: bad code -- https://master.php.net/note/delete/95210/bad+code
Del: spam -- https://master.php.net/note/delete/95210/spam
Del: non-english -- https://master.php.net/note/delete/95210/non-english
Del: in docs -- https://master.php.net/note/delete/95210/in+docs
Del: other reasons-- https://master.php.net/note/delete/95210
Reject -- https://master.php.net/note/reject/95210
Search -- https://master.php.net/manage/user-notes.php