1

I have a class that has this method:

public function user_status()
    {    
            $json = //some code here...
            $result = json_decode($json, true);
            $status = array(
                'key1' => $val1,
                'key2' => $val2
            );
            return $status;

    } 

when calling like this:

$user = new Class();
echo $user->user_status();

it just returns the word Array but when dumping like so:

echo "<pre>User: ", print_r($user->user_status(), TRUE), "</pre>";

it prints the array as expected:

User: Array
(
    [key1] => val1
    [key2] => val2
)

I want to output the array values so I tried calling it like below but its giving me a parse error.

echo $user->user_status()->['key2'];

Whats the proper syntax to output the array values?

4 Answers 4

7

In PHP 5.3 or older:

$array = $user->user_status();
echo $array['key2'];

In PHP 5.4 and newer:

echo $user->user_status()['key2'];

PHP 5.4 introduced array dereferencing which allows us to shorten the syntax a bit.

Sign up to request clarification or add additional context in comments.

4 Comments

You have to echos! not sure why this has been down voted though
I tried the latter approach but its giving me a parse error. must be the php version.
+1 - I like this answer best. Clear and concise. I would add 5.4+ stuff to the top though :)
I like @zavg answer just because the variable naming is more clearer but I will choose this answer for completeness! thanks all for your help.
3

Try

echo $user->user_status()['key2'];

The return value of user_status() itself is an array, so you can "treat the function call as if it would be the name of a variable".

1 Comment

yeah. tried that before but its giving me a parse error. I suspect its because my php version does not support it. but thanks anyway!
3
$status = $user->user_status();
echo $status['key2'];

Comments

2

This is the syntax

$array = $user->user_status();

echo $array['key2'];

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.