Re: Return an Array and immediately reference an index

From: Date: Sat, 12 Apr 2008 07:30:17 +0000
Subject: Re: Return an Array and immediately reference an index
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-272922@lists.php.net to get a copy of this message
Bojan Tesanovic wrote:
On Apr 12, 2008, at 12:33 AM, Daniel Kolbo wrote:
Hello, I want to return an array from function and reference an index all in one line. Is this possible? In the code below I want I want $yo to be the array(5,6). Here is what I've tried, function returnarray() {
    return array('lose' => array(5,6), 'win' => array(9,8));
} $yo = returnarray()['lose']; var_dump($yo); This yields a parse error. function returnarray() {
    return array('lose' => array(5,6), 'win' => array(9,8));
} $yo = {returnarray()}['lose']; var_dump($yo); This yields a parse error. function returnarray() {
    return array('lose' => array(5,6), 'win' => array(9,8));
} $yo = ${returnarray()}['lose']; var_dump($yo); This gives notices as the result of returnarray() is being converted to a string. $yo === NULL...not what i want. function returnarray() {
    return array('lose' => array(5,6), 'win' => array(9,8));
} $yo = returnarray()->['lose']; var_dump($yo); This yields a parse error. function returnarray() {
    return array('lose' => array(5,6), 'win' => array(9,8));
} $yo = ${returnarray()}->['lose']; var_dump($yo); This yields a parse error. Thanks for your help in advance. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
This is not possible in PHP, though you can have a Array wrapper class function returnarray() {
    return new ArrayObject( array('lose' => array(5,6), 'win' => array(9,8)) );
} var_dump (returnarray()->offsetGet('lose')); or even better make you own wrapper class with __set() and __get() methods so you can have var_dump (returnarray()->lose); of course only in PHP5
Well, not quite so fast saying this is only possible in PHP5 You could do something like this. <?php function returnHash() { return (object) array('lose' => array(5,6), 'win' => array(9,8)); } print_r(returnHash()->lose); ?> Basically, this converts your newly built array into an object, using the stdClass object. Then reference the index via an object variable name instead of an array style access method.
Bojan Tesanovic http://www.carster.us/


« previous php.general (#272922) next »