PHP: Can I reference a single member of an array that is returned by a function?

前端 未结 17 1077
抹茶落季
抹茶落季 2020-12-19 00:21

any idea how if the following is possible in PHP as a single line ?:

... It doesn

相关标签:
17条回答
  • 2020-12-19 00:56

    You can use array_slice(), like so:

    $elementX = array_slice(functionThatReturnsAnArray(), $x, 1);
    

    Also noticed that end() is not mentioned. It returns the last element of an array.

    0 讨论(0)
  • 2020-12-19 00:56

    Sometimes I'll change the function, so it can optionally return an element instead of the entire array:

    <?php
    function functionThatReturnsAnArray($n = NULL) {
      return ($n === NULL ? $myArray : $myArray[$n]);
    }
    $firstElement = functionThatReturnsAnArray(0);
    
    0 讨论(0)
  • 2020-12-19 00:59

    @Scott Reynen

    that's not true. This will work:

    list(,,$thirdElement) = $myArray;
    
    0 讨论(0)
  • 2020-12-19 00:59

    I think any of the above would require a comment to explain what you're doing, thus becoming two lines. I find it simpler to do:

    $element = functionThatReturnsArray();
    $element = $element[0];
    

    This way, you're not using an extra variable and it's obvious what you're doing.

    0 讨论(0)
  • 2020-12-19 01:00

    As far as I know this is not possible, I have wanted to do this myself several times.

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