0

I have a PHP function which populates a multi-dimensional array

$client->getResponse()

I want to utilise that array directly, something like this:

echo '$client->getResponse()[0]'; which obviously doesn't work.

I don't want to have to do this

$arr = array($client->getResponse()); as that brings in another level of array which I don't really want.

2
  • Sadly, this is not possible in PHP. The only alternative is method chaining (available since PHP 5) Commented Mar 7, 2011 at 13:13
  • possible duplicate of Access array element from function call in php Commented Mar 8, 2011 at 9:36

4 Answers 4

3
$arr = $client->getResponse();
echo $arr[0];

should suffice.

You can display every item inside the array with a foreach

foreach($client->getResponse() as $clientResponse){
    echo $clientResponse;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Pekka : I don't see how it doesn't answer it... It doesn't bring another array level and can be used directly. Hence, if he got access to his class he could do a chaining : echo $client->getResponse()->get(1); for example.
I'm calling this best response because it is. Works as expected.
1

What about introducing a tmp?

$tmp = $client->getResponse();
echo $tmp[0];

2 Comments

That's what he says he doesn't want to have to do
Wait a second: "$arr = array($client->getResponse()); as that brings in another level of array which I don't really want." The only problem here is the array function.
0

Attention, if you use:

foreach($client->getResponse() ...)

The function ''getResponse'' will be execute in each iteration... If the data change during the "each" process, you may have incoherent values. No ?

1 Comment

Not true. The method will be called only once.
0

Can't you create another method for the class that $client represents? maybe "GetResponseEntry($id)", like so:

function getResponseEntry( $id, $default = null )
{
    static $response = null;

    if( $response === null )
        $response = $this->getResponse();

    if( isset($response[$id]) )
        return $response[$id];
    else
        return $default;
}

Then you could call it like so:

echo $client->getResponseEntry(0);

It may not be suitable for all circumstances, but ... maybe, just maybe, it'll work here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.