Chris Burton
Chris Burton

Reputation: 1205

Fatal error: Cannot use string offset as an array?

In my foreach, I see the following error:

Fatal error: Cannot use string offset as an array [..] on line 97

 88.    foreach ($response as $result) {
 89.        if($result['provider'] == 'Facebook') {
 90.            $provider = 'facebook';
 91.        }else{
 92.            $provider = 'twitter';
 93.        }
 94.        $user = array(
 95.            'provider' => $result['provider'],
 96.            'id' => $result['uid'],
 97.            'name' => $result['info']['name'],
 98.            'image' => $result['info']['image'],
 99.            'link' => $result['info']['urls'][$provider],
100.        );
101.        echo "<h1>".$user['provider']."</h1>";
102.        echo "<p>".$user['id']."</p>";
103.        echo '<p><img src="'.$user['image'].'" /></p>';
105.        echo "<p>".$user['name']."</p>";
106.        echo "<p>".$user['link']."</p>";
107.    }

I've tried reading around the web to understand what the problem is but it seems that some issues are unrelated to mine. I should also just come out with it and let you know I'm not that great with PHP. Can someone lend a hand?

P.S. I added break; after the last echo and that solved it but I don't think that's the way to go about it.

Upvotes: 2

Views: 17914

Answers (3)

Awlad Liton
Awlad Liton

Reputation: 9351

you have used $result['info'] in a loop. it should be sometimes sub array of $result['info'] is not set. It seems that you do not need to run loop. because you will have single user info at a time. or you can use break like this:

foreach ($response as $result) {
    $provider = strtolower($result['provider']);
    $user = array(
        'provider' => $result['provider'],
        'id' => $result['uid'],
        'name' => isset($result['info']['name']) ? $result['info']['name'] : '',
        'image' => isset($result['info']['image']) ? $result['info']['image'] : '',
        'link' => isset($result['info']['urls'][$provider]) ? $result['info']['urls'][$provider] : ''
    );
print_r($user);
    echo "<h1>" . $user['provider'] . "</h1>";
    echo "<p>" . $user['id'] . "</p>";
    echo '<p><img src="' . $user['image'] . '" /></p>';
    echo "<p>" . $user['name'] . "</p>";
    echo "<p>" . $user['link'] . "</p>";
    break;
}

Upvotes: 1

AgileTillIDie
AgileTillIDie

Reputation: 469

$result['info'] is obviously a string and not an array.

Upvotes: 1

Lakatos Gyula
Lakatos Gyula

Reputation: 4150

You declare $result['info'] as a string somewhere then later try to use it as an array. Try to var_dump $result['info'].

Upvotes: 0

Related Questions