Page 1 of 1

Accessing values of a funtions returned array.

Posted: Wed Sep 06, 2006 9:44 am
by RobMcM
Hi

I was wondering if there was a faster way to access a value from an array which is returned from a function.

For example I call this function in a class:

Code: Select all

$class->returnArray();
I want to get a value of that array so normally I would do this:

Code: Select all

$theArray = $class->returnArray();

then

Code: Select all

print( $theArray['thingToPrint'] );
I was wondering if there was a way I could do something like this:

Code: Select all

print( $class->returnArray()['thingToPrint'] );
Effectively selecting a value from the returned array without having to first dump it into a variable.


Thanks in advanced

Posted: Wed Sep 06, 2006 10:08 am
by volka
Is this the normal case, accessing only one element of the entire array?
Then why not add a method to the class that only returns one element? (possible answer: "I'm only using the class" ;))

Posted: Wed Sep 06, 2006 10:18 am
by RobMcM
Yes I could do that but again its more code.

It's not that I am looking for another way to do this but that I want to find a short cut because it's one of those things I have always wondered about.

If you are outputting within html you really only want to output variables rather than do logic and it is annoying having to create variables to query later.

It's not a big issue, just like to find shortcuts like

Code: Select all

<?= $hi ?>
rather than

Code: Select all

<?php print( $hi ); ?>

Ta
[/quote]

Posted: Wed Sep 06, 2006 2:50 pm
by feyd
..and what if your host turns off short tags? Or PHP loses support for them altogether?

Solution: don't use short tags.

Posted: Thu Sep 07, 2006 8:25 am
by RobMcM
I am my host so why would I turn it off??

Anyway that wasn't my question, if you don't know an answer then please don't post mate... simple as.

Posted: Thu Sep 07, 2006 8:34 am
by feyd
I know the answer. Not that I have incentive to give it to you now.

There is no short cut.

Posted: Thu Sep 07, 2006 8:38 am
by RobMcM
I feared as much, thanks for your help anyway!

Posted: Thu Sep 07, 2006 8:53 am
by Jenk
It's not wise to front the admins of a site..

Anyway!

Short-tags will be removed from future versions of PHP - they 'fail' markup standards and finally PHP are pulling their socks up about this.

So your code with shortags will die of death when you try to run it, and in the likely scenario of that happening - all your code will be visible to the end user... != good.

add a method your your class, as posted above.. it's not hard:

Code: Select all

public function getArrayValue($ind)
{
    if (isset($this->array[$ind])) 
    {
        return $this->array[$ind];
    }
    else
    {
        throw new IndexOutOfBoundsException ('Index ' . (int)$ind . ' out of bounds');
    }
}

Posted: Thu Sep 07, 2006 9:11 am
by RobMcM
Thanks but really I wanted to know if there was a PHP shortcut rather than having to amend code.

Thanks anyway