• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Basic PHP] Treat function or method call as an array?

#5
[eluser]janogarcia[/eluser]
Just found this snippet at the PHP documentation (curiosly enough it was submitted a few weeks ago)

http://www.php.net/manual/en/language.ty....php#95210

Quote:If you ever wondered if you can do something like:

Code:
<?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".

Code:
<?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;      
}
?>

This could be an interesting addition to the array_helper.php (I'd modify the error handling routine to be more "CI friendly") if you find yourself using many unnecessary temporary variables.


Messages In This Thread
[Basic PHP] Treat function or method call as an array? - by El Forum - 01-08-2010, 09:23 AM
[Basic PHP] Treat function or method call as an array? - by El Forum - 01-08-2010, 09:30 AM
[Basic PHP] Treat function or method call as an array? - by El Forum - 01-08-2010, 09:38 AM
[Basic PHP] Treat function or method call as an array? - by El Forum - 01-08-2010, 09:45 AM
[Basic PHP] Treat function or method call as an array? - by El Forum - 01-09-2010, 03:28 AM

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.