如何直接使用函数返回的数组[复制]

Possible Duplicate:
Interpreting return value of function directly as an array

Is there a way I can use the following?

$year = getdate()["year"]; ??

If my function returns an array, can I read the value without writing another line?

Thank you for your help!

Yes you can do that without writing newline...

$year = getdate(); $year = $year['year'];

Since PHP 5.4 it is possible to do so:

function fruits()
{
    return array('a' => 'apple', 'b' => 'banana');
}

echo fruits()['a']; # apple

It is called array dereferencing.

Why do you bother about one line ? Just do:

$yearprep = getdate();
$year = $yearprep['year'];

or just let the function return 'year'

What about this? It only takes one line.

$date = date('Y');

See this codepad for results

You can make a proxy function, if you want:

function getPiece($key = 'year')
{
    $tempYear = getDate();
    return $tempYear[$key];
}

echo getPiece();
echo getPiece('day');

The answer is no.

If you really want to do it in one line, you could use the extract construct:

extract(getdate());

or as middus mentions, just use the date function

$year = date('Y');