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

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

    Either current($array) or array_shift($array) will work, the former will leave the array intact.

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

    I actually use a convenience function i wrote for such purposes:

    /**
     * Grabs an element from an array using a key much like array_pop
     */
    function array_key_value($array, $key) {
        if(!empty($array) && array_key_exists($key, $array)) {
            return $array[$key];
        }
        else {
            return FALSE;
        }
    }
    

    then you just call it like so:

    $result = array_key_value(getMeAnArray(), 'arrayKey');
    
    0 讨论(0)
  • 2020-12-19 00:38

    http://us3.php.net/reset

    Only available in php version 5.

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

    Try:

    <?php
    $firstElement = reset(functionThatReturnsAnArray());
    

    If you're just looking for the first element of the array.

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

    nickf, good to know, thanks. Unfortunately that has readability problems beyond a few commas.

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

    Well, I have found a couple of ways to get what you want without calling another function.

    $firstElement = ($t = functionThatReturnsAnArray()) ? $t[0] : false;
    

    and for strings you could use

    $string = (($t = functionThatReturnsAnArray())==0) . $t[0];
    

    .. Interesting problem

    Draco

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