PHP count JSON array

I have searched SO but couldn’t find an answer.My PHP script is receiving some JSON by http post that looks like this:

"task": [
  "task_id": "3",
  "task_due": "Oct 26 11:25",
  "task_completed": "FALSE",
  "task_desc": "fff",
  "task_time": "20131026_112531",
  "task_name": "fff"
  "task_id": "2",
  "task_due": "Oct 26 11:25",
  "task_completed": "FALSE",
  "task_desc": "rff",
  "task_time": "20131026_112522",
  "task_name": "xff"
  "task_id": "1",
  "task_due": "Oct 26 11:25",
  "task_completed": "FALSE",
  "task_desc": "fggg",
  "task_time": "20131026_112516",
  "task_name": "ff"

As you can see, there are 3 items, but when I turn it into a PHP array object and count the items, I’m returned 1, when it should be 3, here is my PHP code:

$json_tasks = $_POST["json_array"];
$task_array = json_decode($json_tasks,true);
echo count($task_array);

And echo count prints out ‘1’ not ‘3’.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Try echo count($task_array['task']);

In general, if you wonder what the structure of the value of a variable $var is, do a

<pre><?php var_export($var, true); ?></pre>

Advantage of this function over alternatives such as serialize and print_r is, that it prints PHP code (and is thus readable by anyone who understands PHP (which is likely if you program in PHP)). Disadvantage of var_export is, that it cannot handle circular structures (e.g. if $a->b == $a), but neither can JSON.

Solution 2

Well the 3 items are in 1 item "task" so, you have one array named task and the 3 elements are in it


echo count($task_array['task']);


please use the below code to print the array in correct pattern

echo '<pre>';

Solution 3

$task_array = json_decode($json_tasks);

EX: 3

From Taiwan

Solution 4

try this code, here i can able to count the number of objects with specific value

here’s my data.json file content


here’s the php code

$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData,true);
$total = 0;
foreach ($data["likes"] as $value) {
        $total = $total+1;
echo $total;

output will be


Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply