Take the 2-minute tour ×

What I'm trying to do is a counter of facebook friends in php, so the result of the code would be something like "You have 1342 Friends!".

So this is the code im using:



    $config = array();
    $config[‘appId’] = 'MY_APP_ID';
    $config[‘secret’] = 'MY_APP_SECRET';
    $facebook = new Facebook($config);
    $user_id = "MY_USER_ID";

      //Get current access_token
    $token_response = file_get_contents

  // known valid access token stored in $token_response
  $access_token = $token_response;

  $code = $_REQUEST["code"];

  //and can get a valid access_token. 
  if (isset($code)) {
      . $app_id  
      . "&client_secret=" . $app_secret 
      . "&code=" . $code . "&display=popup";
    $response = file_get_contents($token_url);
    $params = null;
    parse_str($response, $params);
    $access_token = $params['access_token'];

  // Query the graph - Friends Counter:
$data = file_get_contents
("https://graph.facebook.com/$user_id/friends?" . $access_token );
$friends_count = count($data['data']); 
echo "Friends: $friends_count";

echo "<p>$data</p>"; //to test file_get_contents


So, the result of the echo $Friends_count its always "1".

And then I test $data with an echo and it give me the list of all the friends so it is getting the content but its not counting it right... how could i fix it?

I've already tried changing the



$friends_count = count($data['name']);


$friends_count = count($data['id']);

but the result is always "1".

The result of the above code looks like this;

Friends: 1

{"data":[{"name":"Enny Pichardo","id":"65601304"},{"name":"Francisco Roa","id":"500350497"},etc...]
share|improve this question
you'll have to json_decode() it before count it –  Federico Quagliotto Feb 10 '12 at 17:48
add comment

2 Answers

up vote 2 down vote accepted

You have a JSON object; a string, not anything PHP can "count" with count(). You need to parse the JSON first:

$friends_count = count($obj->data); // This refers to the "data" key in the JSON

Some references I quickly googled:


share|improve this answer
Millions of thanks!! that solve the problem!! didnt new about the JSON object, now learning about it... thanks again!!! –  Hawk Feb 10 '12 at 19:05
add comment

You can get friend count by fql easily.


SELECT friend_count FROM user WHERE uid = me();

https://graph.facebook.com/fql?q=SELECT friend_count FROM user WHERE uid={any id}
share|improve this answer
add comment

Your Answer


