1

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!

Community
  • 1
  • 1
Mo3z
  • 2,138
  • 7
  • 21
  • 29
  • 1
    You can't but it's coming soon. This is also a duplicate of several other questions. Will vote to close when I find a suitable one – Phil Oct 26 '11 at 00:47
  • @Phil This is now possible (I changed my answer), if OP doesn't accept mine or someones correct answer I think we should delete the question. – Dejan Marjanović Aug 31 '12 at 09:42

5 Answers5

1

Why do you bother about one line ? Just do:

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

or just let the function return 'year'

Anonymous
  • 3,679
  • 6
  • 29
  • 40
1

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.

Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
1

You can make a proxy function, if you want:

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

echo getPiece();
echo getPiece('day');
Josh
  • 12,448
  • 10
  • 74
  • 118
  • 1
    `function getPiece($function, $key){$t = $function();return $t[$key];}` this might be better? +1 for idea. – Dejan Marjanović Oct 26 '11 at 01:10
  • @webarto: Good call, that would allow the use of any function, not just getDate(); – Josh Oct 26 '11 at 01:13
  • Josh, I wanted to use this with some inbuilt functions. Thanks for your help.. – Mo3z Oct 26 '11 at 01:20
  • @Moiz: As webarto alluded to, all you'd have to do is make the proxy function call a variably defined function, then you can use it to call any function- builtin or user defined. – Josh Oct 26 '11 at 01:22
0

What about this? It only takes one line.

$date = date('Y');

See this codepad for results

middus
  • 9,103
  • 1
  • 31
  • 33
0

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');
ghbarratt
  • 11,496
  • 4
  • 41
  • 41