Suraj Roy
Suraj Roy

Reputation: 51

Count number of objects in JSON PHP?

I have a JSON array and in that I have 3 JSON objects. I want to count the number of objects that is 3. but it is giving me 1. If I do not add the key "like", then it works. but after adding it, it is not working.

 $JSON = '{"like":['
            . '{"username":"suraj","password":"abc"},'
            . '{"username":"don","password":"abc"},'
            . '{"username":"rana","password":"abc"}'
            . ']}';


    $jsonInPHP = json_decode($JSON);
    echo count($jsonInPHP);

Upvotes: 0

Views: 8959

Answers (3)

R.K.Saini
R.K.Saini

Reputation: 2708

Your JSON represents an object, not an array. In your object, you have like property which is an array so you need to write like this

count($jsonInPHP->like);

Upvotes: 3

JYoThI
JYoThI

Reputation: 12085

pass the second parameter true like this

 $jsonInPHP = json_decode($JSON,true); 
  echo count($jsonInPHP['like']);

Upvotes: 4

u_mulder
u_mulder

Reputation: 54831

This happens because after json decoding your string you get object with one property (like) (or array with one element with key like).

In both ways you want to count size of this property (or key) which is:

// if $jsonInPHP is array
echo count($jsonInPHP['like']); 
// if $jsonInPHP is object
echo count($jsonInPHP->like);

Upvotes: 1

Related Questions