Ну как всегда, выскажу свое мнение:
Итак, нашего бульдога ставят на охрану только в случаях неопределенности, таких случаев очень мало, например раньше часто использовали при удалении файлов, инклудов. Сейчас реже и реже. Смысл в том что ваш код по дефолту должен работать без каких либо ошибок, если вам нужно засунуть в count
объект, то можно использовать типа:
count(get_object_vars($OBJECT))
Делать такое можно, НО вы должны понимать, что вызывая собаку вы замедляете работу скрипта. На глазок самым долгим будет count
с генерацией ошибки (вообще любая генерация ошибки очень ресурсоемкая и долгая, поэтому и избегают), потом будет идти @count
и самый быстрый вариант count
без ошибки.
Теперь осталось определить, к чему ближе @
к первому варианту(самому долгому) или к последнему (самому быстрому). Скорей к первому, почему, потому-что собака подавляет не все виды ошибок, а лишь некоторые, например ParseError
будет и с собакой приводить к критической ошибке. В двух словах схема такова: возникает ошибка, вызывается генератор ошибок, он определяет ошибку (это уже ресурсоемкий процесс), дальше проверяет может ли собака его подавить, если да то заканчиваем дело, если нет — выбиваем критулю.
Я под юбку интерпретатору не заглядывал, но вроде как так. Сама концепция — одинаковая, собаки — плохо, кошки лучше, особено британские либо шотландские
Peter383 0 / 0 / 0 Регистрация: 16.01.2019 Сообщений: 7 |
||||||||
1 |
||||||||
15.03.2019, 21:26. Показов 12614. Ответов 6 Метки нет (Все метки)
Добрый день.
Ругается на строку
Подскажите, какой код написать, чтобы корректно обработать ошибку. Спасибо.
0 |
3827 / 3178 / 1334 Регистрация: 01.08.2012 Сообщений: 10,768 |
|
15.03.2019, 21:33 |
2 |
Что лежит в $comments, какой тип данных? Проверить можно с помощью var_dump().
0 |
sash23 524 / 381 / 245 Регистрация: 31.05.2016 Сообщений: 1,038 |
||||||||||||
15.03.2019, 21:51 |
3 |
|||||||||||
Сообщение было отмечено Peter383 как решение РешениеКак-то так:
если это массив то будет возвращено количество элементов в нём а иначе 0. Добавлено через 1 минуту
можно заменить на
1 |
0 / 0 / 0 Регистрация: 16.01.2019 Сообщений: 7 |
|
16.03.2019, 23:17 [ТС] |
4 |
Спасибо, ошибка исчезла.
0 |
0 / 0 / 0 Регистрация: 05.02.2020 Сообщений: 1 |
|
05.02.2020, 11:14 |
5 |
Добрый день ругается вот на это что можно с этим сделать
0 |
Модератор 2315 / 1540 / 680 Регистрация: 13.03.2010 Сообщений: 5,204 |
|
05.02.2020, 11:18 |
6 |
Hobbits, что находится в
0 |
340 / 160 / 89 Регистрация: 16.01.2020 Сообщений: 771 |
|
05.02.2020, 18:16 |
7 |
судя по тому, что Вы разбиваете $ids как строку, $arr_ids = explode ( ‘,’, $ids );
0 |
(PHP 4, PHP 5, PHP 7, PHP
count — Подсчитывает количество элементов массива или Countable объекте
Описание
count(Countable|array $value
, int $mode
= COUNT_NORMAL
): int
Список параметров
-
value
-
Массив или объект, реализующий Countable.
-
mode
-
Если необязательный параметр
mode
установлен в
COUNT_RECURSIVE
(или 1), count()
будет рекурсивно подсчитывать количество элементов массива.
Это особенно полезно для подсчёта всех элементов многомерных
массивов.Предостережение
count() умеет определять рекурсию для избежания
бесконечного цикла, но при каждом обнаружении выводит ошибку уровня
E_WARNING
(в случае, если массив содержит себя
более одного раза) и возвращает большее количество, чем могло бы
ожидаться.
Возвращаемые значения
Возвращает количество элементов в value
.
До PHP 8.0.0, если параметр не был ни массивом (array), ни объектом (object), реализующим интерфейс Countable,
возвращалось 1
,
если значение параметра value
не было null
,
в этом случае возвращалось 0
.
Список изменений
Версия | Описание |
---|---|
8.0.0 |
count() теперь выбрасывает TypeError, если передан недопустимый исчисляемый тип в параметр value .
|
7.2.0 |
count() теперь будет выдавать предупреждение о недопустимых исчисляемых типах, переданных в параметр value .
|
Примеры
Пример #1 Пример использования count()
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
var_dump(count($b));
?>
Результат выполнения данного примера:
Пример #2 Пример использования count() с неисчисляемым типом (плохой пример — не делайте так)
<?php
$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
var_dump(count($b));var_dump(count(null));var_dump(count(false));
?>
Результат выполнения данного примера:
Результат выполнения данного примера в PHP 7.2:
int(3) Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 int(0) Warning: count(): Parameter must be an array or an object that implements Countable in … on line 14 int(1)
Результат выполнения данного примера в PHP 8:
int(3) Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable .. on line 12
Пример #3 Пример рекурсивного использования count()
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));// рекурсивный подсчёт
var_dump(count($food, COUNT_RECURSIVE));// обычный подсчёт
var_dump(count($food));?>
Результат выполнения данного примера:
Пример #4 Объект, реализующий интерфейс Countable
<?php
class CountOfMethods implements Countable
{
private function someMethod()
{
}
public function
count(): int
{
return count(get_class_methods($this));
}
}$obj = new CountOfMethods();
var_dump(count($obj));
?>
Результат выполнения данного примера:
Смотрите также
- is_array() — Определяет, является ли переменная массивом
- isset() — Определяет, была ли установлена переменная значением, отличным от null
- empty() — Проверяет, пуста ли переменная
- strlen() — Возвращает длину строки
- is_countable() — Проверить, что содержимое переменной является счётным значением
- Массивы
onlyranga at gmail dot com ¶
9 years ago
[Editor's note: array at from dot pl had pointed out that count() is a cheap operation; however, there's still the function call overhead.]
If you want to run through large arrays don't use count() function in the loops , its a over head in performance, copy the count() value into a variable and use that value in loops for a better performance.
Eg:
// Bad approach
for($i=0;$i<count($some_arr);$i++)
{
// calculations
}
// Good approach
$arr_length = count($some_arr);
for($i=0;$i<$arr_length;$i++)
{
// calculations
}
asma mechtaba ¶
1 year ago
count and sizeof are aliases, what work for one works for the other.
lucasfsmartins at gmail dot com ¶
4 years ago
If you are on PHP 7.2+, you need to be aware of "Changelog" and use something like this:
<?php
$countFruits = is_array($countFruits) || $countFruits instanceof Countable ? count($countFruits) : 0;
?>
You can organize your code to ensure that the variable is an array, or you can extend the Countable so that you don't have to do this check.
Anonymous ¶
3 years ago
For a Non Countable Objects
$count = count($data);
print "Count: $countn";
Warning: count(): Parameter must be an array or an object that implements Countable in example.php on line 159
#Quick fix is to just cast the non-countable object as an array..
$count = count((array) $data);
print "Count: $countn";
Count: 250
Christoph097 ¶
1 year ago
Empty values are counted:
<?php
$ar[] = 3;
$ar[] = null;
var_dump(count($ar)); //int(2)
?>
danny at dannymendel dot com ¶
15 years ago
I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.
// $limit is set to the number of recursions
<?php
function count_recursive ($array, $limit) {
$count = 0;
foreach ($array as $id => $_array) {
if (is_array ($_array) && $limit > 0) {
$count += count_recursive ($_array, $limit - 1);
} else {
$count += 1;
}
}
return $count;
}
?>
olja dot fb at gmail dot com ¶
6 days ago
In example #3, given as:
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));// recursive count
var_dump(count($food, COUNT_RECURSIVE));
?>
with the output given as int(8), it may have some readers mistaken, as I was at first: one might take it as keys being counted as well as the inner array entries:
<?php
// NO:
'fruits', 'orange', 'banana', 'apple',
'veggie', 'carrot', 'collard', 'pea'
?>
But actually keys are not counted in count function, and why it is still 8 - because inner arrays are counted as entries as well as their inner elements:
<?php
// YES:
array('orange', 'banana', 'apple'), 'orange', 'banana', 'apple',
array('carrot', 'collard', 'pea'), 'carrot', 'collard', 'pea'
?>
alexandr at vladykin dot pp dot ru ¶
16 years ago
My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).
<?php
function getArrCount ($arr, $depth=1) {
if (!is_array($arr) || !$depth) return 0;
$res=count($arr);
foreach (
$arr as $in_ar)
$res+=getArrCount($in_ar, $depth-1);
return
$res;
}
?>
pied-pierre ¶
7 years ago
A function of one line to find the number of elements that are not arrays, recursively :
function count_elt($array, &$count=0){
foreach($array as $v) if(is_array($v)) count_elt($v,$count); else ++$count;
return $count;
}
php_count at cubmd dot com ¶
6 years ago
All the previous recursive count solutions with $depth option would not avoid infinite loops in case the array contains itself more than once.
Here's a working solution:
<?php
/**
* Recursively count elements in an array. Behaves exactly the same as native
* count() function with the $depth option. Meaning it will also add +1 to the
* total count, for the parent element, and not only counting its children.
* @param $arr
* @param int $depth
* @param int $i (internal)
* @return int
*/
public static function countRecursive(&$arr, $depth = 0, $i = 0) {
$i++;
/**
* In case the depth is 0, use the native count function
*/
if (empty($depth)) {
return count($arr, COUNT_RECURSIVE);
}
$count = 0;
/**
* This can occur only the first time when the method is called and $arr is not an array
*/
if (!is_array($arr)) {
return count($arr);
}
// if this key is present, it means you already walked this array
if (isset($arr['__been_here'])) {
return 0;
}
$arr['__been_here'] = true;
foreach (
$arr as $key => &$value) {
if ($key !== '__been_here') {
if (is_array($value) && $depth > $i) {
$count += self::countRecursive($value, $depth, $i);
}
$count++;
}
}
// you need to unset it when done because you're working with a reference...
unset($arr['__been_here']);
return $count;
}
?>
Gerd Christian Kunze ¶
9 years ago
Get maxWidth and maxHeight of a two dimensional array..?
Note:
1st dimension = Y (height)
2nd dimension = X (width)
e.g. rows and cols in database result arrays
<?php
$TwoDimensionalArray = array( 0 => array( 'key' => 'value', ...), ... );
?>
So for Y (maxHeight)
<?php
$maxHeight = count( $TwoDimensionalArray )
?>
And for X (maxWidth)
<?php
$maxWidth = max( array_map( 'count', $TwoDimensionalArray ) );
?>
Simple? ;-)
buyatv at gmail dot com ¶
6 years ago
You can not get collect sub array count when there is only one sub array in an array:
$a = array ( array ('a','b','c','d'));
$b = array ( array ('a','b','c','d'), array ('e','f','g','h'));
echo count($a); // 4 NOT 1, expect 1
echo count($b); // 2, expected
JumpIfBelow ¶
8 years ago
As I see in many codes, don't use count to iterate through array.
Onlyranga says you could declare a variable to store it before the for loop.
I agree with his/her approach, using count in the test should be used ONLY if you have to count the size of the array for each loop.
You can do it in the for loop too, so you don't have to "search" where the variable is set.
e.g.
<?php
$array = [1, 5, 'element'];
for($i = 0, $c = count($array); $i < $c; $i++)
var_dump($array[$i]);
?>
buyatv at gmail dot com ¶
6 years ago
You can not get collect sub array count when use the key on only one sub array in an array:
$a = array("a"=>"appple", b"=>array('a'=>array(1,2,3),'b'=>array(1,2,3)));
$b = array("a"=>"appple", "b"=>array(array('a'=>array(1,2,3),'b'=>array(1,2,3)), array(1,2,3),'b'=>array(1,2,3)), array('a'=>array(1,2,3),'b'=>array(1,2,3))));
echo count($a['b']); // 2 NOT 1, expect 1
echo count($b['b']); // 3, expected
vojtaripa at gmail dot com ¶
2 years ago
To get the count of the inner array you can do something like:
$inner_count = count($array[0]);
echo ($inner_count);
ThisIsNotImportant ¶
7 years ago
About 2d arrays, you have many way to count elements :
<?php
$MyArray = array ( array(1,2,3),
1,
'a',
array('a','b','c','d') );// All elements
echo count($MyArray ,COUNT_RECURSIVE); // output 11 (9 values + 2 arrays)
// First level elements
echo count($MyArray ); // output 4 (2 values+ 2 arrays)
// Both level values, but only values
echo(array_sum(array_map('count',$MyArray ))); //output 9 (9 values)
// Only second level values
echo (count($MyArray ,COUNT_RECURSIVE)-count($MyArray )); //output 7 ((all elements) - (first elements))
?>
max at schimmelmann dot org ¶
3 years ago
In special situations you might only want to count the first level of the array to figure out how many entries you have, when they have N more key-value-pairs.
<?php
$data
= [
'a' => [
'bla1' => [
0 => 'asdf',
1 => 'asdf',
2 => 'asdf',
],
'bla2' => [
0 => 'asdf',
1 => 'asdf',
2 => 'asdf',
],
'bla3' => [
0 => 'asdf',
1 => 'asdf',
2 => 'asdf',
],
'bla4' => [
0 => 'asdf',
1 => 'asdf',
2 => 'asdf',
],
],
'b' => [
'bla1' => [
0 => 'asdf',
1 => 'asdf',
2 => 'asdf',
],
'bla2' => [
0 => 'asdf',
1 => 'asdf',
2 => 'asdf',
],
],
'c' => [
'bla1' => [
0 => 'asdf',
1 => 'asdf',
2 => 'asdf',
]
]
];
$count = array_sum(array_values(array_map('count', $data)));
// will return int(7)
var_dump($count);// will return 31
var_dump(count($data, 1));
?>
XavDeb ¶
3 years ago
If you want to know the sub-array containing the MAX NUMBER of values in a 3 dimensions array, here is a try (maybe not the nicest way, but it works):
function how_big_is_the_biggest_sub ($array) {
// we parse the 1st level
foreach ($array AS $key => $array_lvl2) {
//within level 2, we count the 3d levels max
$lvl2_nb = array_map( 'count', $array_lvl2) ;
$max_nb = max($lvl2_nb);
// we store the matching keys, it might be usefull
$max_key = array_search($max_nb, $lvl2_nb);
$max_nb_all[$max_key.'|'.$key] = $max_nb;
}
// now we want the max from all levels 2, so one more time
$real_max = max($max_nb_all);
$real_max_key = array_search($real_max, $max_nb_all);
list($real_max_key2, $real_max_key1) = explode('|', $real_max_key);
// preparing result
$biggest_sub['max'] = $real_max;
$biggest_sub['key1'] = $real_max_key1;
$biggest_sub['key2'] = $real_max_key2;
return $biggest_sub;
}
/*
$cat_poids_max['M']['Juniors'][] = 55;
$cat_poids_max['M']['Juniors'][] = 61;
$cat_poids_max['M']['Juniors'][] = 68;
$cat_poids_max['M']['Juniors'][] = 76;
$cat_poids_max['M']['Juniors'][] = 100;
$cat_poids_max['M']['Seniors'][] = 55;
$cat_poids_max['M']['Seniors'][] = 60;
$cat_poids_max['M']['Seniors'][] = 67;
$cat_poids_max['M']['Seniors'][] = 75;
$cat_poids_max['M']['Seniors'][] = 84;
$cat_poids_max['M']['Seniors'][] = 90;
$cat_poids_max['M']['Seniors'][] = 100;
//....
$cat_poids_max['F']['Juniors'][] = 52;
$cat_poids_max['F']['Juniors'][] = 65;
$cat_poids_max['F']['Juniors'][] = 74;
$cat_poids_max['F']['Juniors'][] = 100;
$cat_poids_max['F']['Seniors'][] = 62;
$cat_poids_max['F']['Seniors'][] = 67;
$cat_poids_max['F']['Seniors'][] = 78;
$cat_poids_max['F']['Seniors'][] = 86;
$cat_poids_max['F']['Seniors'][] = 100;
*/
$biggest_sub = how_big_is_the_biggest_sub($cat_poids_max);
echo "<li> ".$biggest_sub['key1']." ==> ".$biggest_sub['key2']." ==> ".$biggest_sub['max']; // displays : M ==> Seniors ==> 7
So I upgraded to PHP 8 and ran my script which gave me this error:
Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given in C:xampphtdocsappincludesfunctionscreate_session.php:78
Stack trace:
#0 C:xampphtdocspublicfront_desk.php(508): Session->check_subfeature_access(22, 0)
#1 {main} thrown in C:xampphtdocsappincludesfunctionscreate_session.php on line 78
Which turned out to be due to a new update in PHP 8 that doesn’t allow non-array values to be used in the count function and throws a fatal error stopping the further script execution. For example, if you have a $_POST['checkboxes_checked']
and you do count($_POST['checkboxes_checked'])
then it will give the above error because by default it doesn’t recognize it as an array. To fix this error, you can do: count((array)$_POST['checkboxes_checked']))
, which fixes the problem.
However, the problem in my case is that I have a couple of hundred files that need this problem fixed, I don’t want to go inside each file and fix this as that would be extremely time-consuming. Is there a way to configure PHP 8 to ignore this and still proceed with the count function with these $_POST parameters? or some sort of search/replace regex that I can run on all files that replace count($_POST['some_parameter_name'])
with count((array)$_POST['some_parameter_name']))
? Honestly, I have no idea how I can fix this problem without manually going into each file, and this is the part where I need your help.
asked Oct 31, 2022 at 12:39
Syed M. SannanSyed M. Sannan
1,0052 gold badges8 silver badges26 bronze badges
22
One temporary solution would be to define your own count()
function. For instance:
/**
* @deprecated Temporary solution for count() TypeError on invalid countables
*/
function oldCount($input)
{
return isset($input) && is_array($input) ? count($input) : 0;
}
This is just a quick example. You should ideally use your (array)
prefix.
Now all you need to do is replace all the occurrences of count(
in your code with oldCount(
, and you’re done.
WARNING: This is only meant to be a temporary solution. It requires an extra function call every time it is used and PHP 8 has not incorporated a stricter without reason: It’s there to protect you. Update your code as soon as possible.
answered Oct 31, 2022 at 12:53
KIKO SoftwareKIKO Software
14.7k3 gold badges16 silver badges32 bronze badges
6
In this guide, we will discuss the «Warning: count(): Parameter must be an array or an object that implements Countable» error in PHP and provide a step-by-step solution to fix it. This error occurs when the count()
function is used with a variable that is not an array or an object implementing the Countable
interface.
Table of Contents
- Understanding the Countable Interface
- Why the Error Occurs
- Fixing the Error
- FAQ
- Related Links
Understanding the Countable Interface
The Countable
interface is part of the Standard PHP Library (SPL) and allows objects to be counted using the count()
function. To implement this interface, a class must define a count()
method that returns the number of elements in the object.
Here’s an example of a class implementing the Countable
interface:
class MyCollection implements Countable
{
private $items = [];
public function addItem($item)
{
$this->items[] = $item;
}
public function count()
{
return count($this->items);
}
}
$collection = new MyCollection();
$collection->addItem('Item 1');
$collection->addItem('Item 2');
echo count($collection); // 2
Why the Error Occurs
The «Parameter must be an array or an object that implements Countable» error occurs when you pass a variable to the count()
function that is not an array or an object implementing the Countable
interface. This often happens when the variable is uninitialized, null
, or contains a scalar value (e.g., string, integer, float, or boolean).
For example, the following code will produce the error:
$string = 'Hello World';
$result = count($string); // Warning: count(): Parameter must be an array or an object that implements Countable
This error became more prevalent from PHP version 7.2 onwards, as the count()
function’s behavior was changed to emit a warning when used with non-countable types.
Fixing the Error
To fix the «Parameter must be an array or an object that implements Countable» error, you need to ensure that the variable passed to the count()
function is either an array or an object implementing the Countable
interface.
Here are a few ways to achieve this:
Check if the Variable is an Array or an Object Implementing Countable
Before calling the count()
function, you can use the is_array()
function or the instanceof
operator to check if the variable is countable:
if (is_array($variable) || $variable instanceof Countable) {
$result = count($variable);
} else {
// Handle the non-countable case
}
Provide a Default Value for the Variable
If you know that the variable should always be an array or an object implementing Countable
, you can provide a default value for it, ensuring that it’s always countable:
// Initialize the variable as an empty array
$items = [];
// Add items to the array
$items[] = 'Item 1';
$items[] = 'Item 2';
// This will not produce an error, as $items is an array
$result = count($items);
Use a Ternary Operator to Provide a Default Count
You can use a ternary operator to provide a default count when the variable is not countable:
$result = (is_array($variable) || $variable instanceof Countable) ? count($variable) : 0;
FAQ
1. What is the Countable interface in PHP?
The Countable
interface is part of the Standard PHP Library (SPL) and allows objects to be counted using the count()
function. A class must implement the count()
method to be considered countable.
2. When was the count() function’s behavior changed?
The count()
function’s behavior was changed in PHP 7.2 to emit a warning when used with non-countable types.
3. What types of variables can be passed to the count() function without causing an error?
Only arrays and objects implementing the Countable
interface can be passed to the count()
function without causing an error.
4. How can I check if a variable is countable in PHP?
You can use the is_array()
function or the instanceof
operator to check if a variable is countable:
if (is_array($variable) || $variable instanceof Countable) {
// The variable is countable
}
5. How can I provide a default count for non-countable variables?
You can use a ternary operator to provide a default count when the variable is not countable:
$result = (is_array($variable) || $variable instanceof Countable) ? count($variable) : 0;
- PHP: Countable — Manual
- PHP: count — Manual
- PHP: is_array — Manual
- PHP: The instanceof Operator — Manual