scott
scott

Reputation: 3202

Undefined index: user in php

i have following array which is generated from my object

Laravel\Socialite\Two\User Object
(
    [token] => some token valuw
    [id] => 12345567769667
    [nickname] => 
    [name] => user name
    [email] => [email protected]

    [user] => Array
        (
            [kind] => plus

            [gender] => male
            [emails] => Array
                (
                    [0] => Array
                        (
                            [value] => [email protected]
                            [type] => account
                        )

                )
        )
)

if i try to access id nickname,name,email like

echo $user->id;

it display output. if i try to access

echo $user->user->gender;

or

echo $user['user']['gender'];

then it throw error as undefined index user

how i can access gender and email value ?

thank you

Upvotes: 2

Views: 723

Answers (2)

aldrin27
aldrin27

Reputation: 3407

Try this:

 echo $user->user['gender'];

To access email value:

$emailVal = [];
foreach($user->user['emails'] as $key => $val) {
  $emailVal[] = ['value' => $val['value'], 'type' => $val['type']];
}

print_r($emailVal);

Or if you want to access only email:

 echo $user->user['emails'][0]['value'];

Upvotes: 1

jitendrapurohit
jitendrapurohit

Reputation: 9675

$user is an object and user is an array

if (property_exists($user, user) && !empty($user->user[gender])) {
  $user->user[gender]; // to access gender
  $user->user[emails]; // to access email
}

to avoid notices and warnings

Upvotes: 2

Related Questions