0

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);
5
  • count($jsonInPHP['like']) or count($jsonInPHP->like) Commented Aug 27, 2016 at 11:29
  • $jsonInPHP = json_decode($JSON,true); echo count($jsonInPHP['like']); Commented Aug 27, 2016 at 11:30
  • Note: If you set the 2nd param as true it makes it an associative array. Commented Aug 27, 2016 at 11:30
  • thanks ... $jsonInPHP->like did this for me Commented Aug 27, 2016 at 12:13
  • what if I want to count all the usernames only ? Commented Jul 20, 2018 at 5:37

3 Answers 3

4

pass the second parameter true like this

 $jsonInPHP = json_decode($JSON,true); 
  echo count($jsonInPHP['like']);
Sign up to request clarification or add additional context in comments.

1 Comment

adding true gives error,, though i got solution,, count($jsonInPHP->like);
3

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);

Comments

1

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);

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.