Getting element from PHP array returned by function

后端 未结 7 1080
野趣味
野趣味 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
    
    0 讨论(0)
  • 2020-12-11 01:44

    Yes, php can't do that. Bat you can use ArrayObect, like so:

    $item = getSomeArray()->{1};
    // Credits for curly braces for Bracketworks    
    
    function getSomeArray(){
         $ret = Array();
         $ret[0] = 0;
         $ret[1] = 100;
         return new ArrayObject($ret, ArrayObject::ARRAY_AS_PROPS);
    }
    

    Okay, maybe not working with numeric keys, but i'm not sure.

    0 讨论(0)
  • 2020-12-11 01:46

    As the others says, there is no direct way to do this, I usually just assign it to a variable like so:

    $items = getSomeArray();
    $item = $items[1];
    
    
    function getSomeArray(){
        $ret = Array();
        $ret[0] = 0;
        $ret[1] = 100;
        return $ret;
    }
    
    0 讨论(0)
  • 2020-12-11 01:48

    I know this is an old question, but, in your example, you could also use array_pop() to get the last element of the array, (or array_shift() to get the first).

    <?php
    $item = array_pop(getSomeArray());
    
    
    function getSomeArray(){
        $ret = Array();
        $ret[0] = 0;
        $ret[1] = 100;
        return $ret;
    }
    
    0 讨论(0)
  • 2020-12-11 01:51

    PHP 5.4 has added Array Dereferencing, here's the example from PHP's Array documentation:

    Example #7 Array dereferencing

    function getArray() {
        return ['a', 'b', 'c'];
    }
    
    // PHP 5.4
    $secondElement = getArray()[0]; // output = a
    
    // Previously
    $tmp = getArray();
    $secondElement = $tmp[0]; // output = a
    
    0 讨论(0)
  • 2020-12-11 01:57

    I am fairly certain that is not possible to do in PHP. You have to assign the returned array to another array before you can access the elements within or use it directly in some other function that will iterate though the returned array (i.e. var_dump(getSomeArray()) ).

    0 讨论(0)
提交回复
热议问题