Getting element from PHP array returned by function

后端 未结 7 1086
野趣味
野趣味 2020-12-11 01:10

I\'m not sure if this is possible, but I can\'t figure out how to do it if it is...

I want to get a specific element out of an array that is returned by a function,

7条回答
  •  温柔的废话
    2020-12-11 01:43

    The syntax you're referring to is known as function array dereferencing. It's not yet implemented and there's an RFC for it.

    The generally accepted syntax is to assign the return value of the function to an array and access the value from that with the $array[1]syntax.

    That said, however you could also pass the key you want as an argument to your function.

    function getSomeArray( $key = null ) {
      $array = array(
         0 => "cheddar",
         1 => "wensleydale"
      );
    
      return is_null($key) ? $array : isset( $array[$key] ) ? $array[$key] : false;    
    }
    
    echo getSomeArray(0); // only key 0
    echo getSomeArray(); // entire array
    

提交回复
热议问题