Nababur's avatar
Level 43

How can i fix the error . must be of type Countable|array, null given ?

const data = {

    employes: {{ count($companies) }},

    users: {{ count($users) }},

    jobs: {{ count($activeJobs) }}

    };
0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The error "must be of type Countable|array, null given" occurs when you try to use the count() function on a variable that is not an array or does not implement the Countable interface. In this case, it seems that one or more of the variables $companies, $users, or $activeJobs is null.

To fix this error, you can check if the variables are null before using the count() function. Here's an example of how you can modify the code to handle null values:

const data = {
    employes: {{ $companies ? count($companies) : 0 }},
    users: {{ $users ? count($users) : 0 }},
    jobs: {{ $activeJobs ? count($activeJobs) : 0 }}
};

In the modified code, we use the ternary operator (?) to check if the variables are null. If they are not null, we use the count() function as before. Otherwise, we use a default value of 0.

Note: Make sure to replace the {{ }} with the appropriate syntax for your template engine or JavaScript framework.

JussiMannisto's avatar

The error message tells you everything you need to know. If you want to count a variable, it has to be either an array or a Countable. One or more of your variables is null, so you need to fix that.

Lary's answer hides the error instead of solving the issue.

iamsagarvaghela's avatar

Hey, @nababur You are getting non-array values as a response over here that's why the error occurs. You can simply solve it as below logic:

<?php
//Error case
$data = 10;
echo is_array($data) ? count($data) : $data;
echo "\n";

//This case it works
$data = [5, 2, 6, 5];
echo is_array($data) ? count($data) : $data;
?>

Try to execute those things in the compiler you will get the solution. šŸ‘šŸ»

Please or to participate in this conversation.