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

前端 未结 17 1076
抹茶落季
抹茶落季 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:40

    I am guessing that this is a built-in or library function, since it sounds like you cannot edit it directly. I recommend creating a wrapper function to give you the output you need:

    function functionThatReturnsOneElement( $arg )
    {
        $result = functionThatReturnsAnArray( $arg );
        return $result[0];
    }
    $firstElement = functionThatReturnsOneElement();
    
    0 讨论(0)
  • 2020-12-19 00:42

    You can do this in one line! Use array_shift().

    <?php
    
    echo array_shift(i_return_an_array());
    
    function i_return_an_array() {
        return array('foo', 'bar', 'baz');
    }
    

    When this is executed, it will echo "foo".

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

    Unfortunately, that is not possible with PHP. You have to use two lines to do it.

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

    list() is useful here. With any but the first array element, you'll need to pad it with useless variables. For example:

    list( $firstElement ) = functionThatReturnsAnArray();
    list( $firstElement , $secondElement ) = functionThatReturnsAnArray();
    

    And so on.

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

    If it's always the first element, you should probably think about having the function return just the first item in the array. If that is the most common case, you could use a little bit of coolness:

    function func($first = false) {
        ...
        if $first return $array[0];
        else return $array;
    }
    
    $array = func();
    $item = func(true);
    

    My php is slightly rusty, but i'm pretty sure that works.

    You can also look at array_shift() and array_pop().

    This is probably also possible:

    array(func())[0][i];
    

    The 0 is for the function.

    0 讨论(0)
  • 2020-12-19 00:49
    $firstItem = current(returnsArray());
    
    0 讨论(0)
提交回复
热议问题