470,870 Members | 1,475 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,870 developers. It's quick & easy.

perl style in php ?

Often I just want to be able to get at a single element from a
function that returns an array. For example, if I just want the
current year I need to write:
$today = getdate();
$year = $today['year'];
Call me lazy but this is two steps to return a single value.
In perl I can nest these two step together into something like:

$year = ( $getdate() )['year'];
I've tried to get several variations of this to work in php but I
don't seem to be having any luck.

Is this style possible in php?

Thanks,
crub
Jul 17 '05 #1
2 1527
crub wrote:
Call me lazy but this is two steps to return a single value.
In perl I can nest these two step together into something like:

$year = ( $getdate() )['year'];
I've tried to get several variations of this to work in php but I
don't seem to be having any luck.

Is this style possible in php?


Not quite, although PHP 5 introduces object dereferencing, which comes
close:

<?php

function array2object($array) {
$obj = new stdClass;

foreach ($array as $k => $v) {
$obj->$k = $v;
}

return $obj;
}

$array = array('name' => 'joe');
print array2object($array)->name;

?>

Indexed arrays can be parsed the usual way through the list() function.
JW

Jul 17 '05 #2
cr**@volcanomail.com (crub) wrote in message news:<e4**************************@posting.google. com>...
Often I just want to be able to get at a single element from a
function that returns an array. For example, if I just want the
current year I need to write:
$today = getdate();
$year = $today['year'];
Call me lazy but this is two steps to return a single value.
In perl I can nest these two step together into something like:

$year = ( $getdate() )['year'];
I've tried to get several variations of this to work in php but I
don't seem to be having any luck.

Is this style possible in php?


No. What I often do in this situation is use extract(). Example:

extract(getdate());
// $year, $mon, $seconds, etc. are now set
Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Premshree Pillai | last post: by
3 posts views Thread by lonelyplanet999 | last post: by
reply views Thread by Fred | last post: by
385 posts views Thread by Xah Lee | last post: by
reply views Thread by Xah Lee | last post: by
5 posts views Thread by Robert Oschler | last post: by
13 posts views Thread by Corey G. | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.