Как найти сколько элементов в массиве

(PHP 4, PHP 5, PHP 7, PHP 8)

countCounts all elements in an array or in a Countable object

Description

count(Countable|array $value, int $mode = COUNT_NORMAL): int

Parameters

value

An array or Countable object.

mode

If the optional mode parameter is set to
COUNT_RECURSIVE (or 1), count()
will recursively count the array. This is particularly useful for
counting all the elements of a multidimensional array.

Caution

count() can detect recursion to avoid an infinite
loop, but will emit an E_WARNING every time it
does (in case the array contains itself more than once) and return a
count higher than may be expected.

Return Values

Returns the number of elements in value.
Prior to PHP 8.0.0, if the parameter was neither an array nor an object that
implements the Countable interface,
1 would be returned,
unless value was null, in which case
0 would be returned.

Changelog

Version Description
8.0.0 count() will now throw TypeError on
invalid countable types passed to the value parameter.
7.2.0 count() will now yield a warning on invalid countable types
passed to the value parameter.

Examples

Example #1 count() example


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

The above example will output:

Example #2 count() non Countable|array example (bad example — don’t do this)


<?php
$b
[0] = 7;
$b[5] = 9;
$b[10] = 11;
var_dump(count($b));var_dump(count(null));var_dump(count(false));
?>

The above example will output:

Output of the above example in 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)

Output of the above example in PHP 8:

int(3)

Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable .. on line 12

Example #3 Recursive count() example


<?php
$food
= array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));// recursive count
var_dump(count($food, COUNT_RECURSIVE));// normal count
var_dump(count($food));?>

The above example will output:

Example #4 Countable object


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

The above example will output:

See Also

  • is_array() — Finds whether a variable is an array
  • isset() — Determine if a variable is declared and is different than null
  • empty() — Determine whether a variable is empty
  • strlen() — Get string length
  • is_countable() — Verify that the contents of a variable is a countable value
  • Arrays

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

11 hours 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


The question is simple: given a C++ array (e.g. x as in int x[10]), how would you get the number of elements in it?

An obvious solution is the following macro (definition 1):

#define countof( array ) ( sizeof( array )/sizeof( array[0] ) )

I cannot say this isn’t correct, because it does give the right answer when you give it an array. However, the same expression gives you something bogus when you supply something that is not an array. For example, if you have

int * p;

then countof( p ) always give you 1 on a machine where an int pointer and an int have the same size (e.g. on a Win32 platform).

This macro also wrongfully accepts any object of a class that has a member function operator[]. For example, suppose you write

class IntArray {
private:
    int * p;
    size_t size;
public:
    int & operator [] ( size_t i );
} x;

then sizeof( x ) will be the size of the x object, not the size of the buffer pointed to by x.p. Therefore you won’t get a correct answer by countof( x ).

So we conclude that definition 1 is not good because the compiler does not prevent you from misusing it. It fails to enforce that only an array can be passed in.

What is a better option?

Well, if we want the compiler to ensure that the parameter to countof is always an array, we have to find a context where only an array is allowed. The same context should reject any non-array expression.

Some beginners may try this (definition 2):

template <typename T, size_t N>
size_t countof( T array[N] )
{
   return N;
}

They figure, this template function will accept an array of N elements and return N.

Unfortunately, this doesn’t compile because C++ treats an array parameter the same as a pointer parameter, i.e. the above definition is equivalent to:

template <typename T, size_t N>
size_t countof( T * array )
{
    return N;
}

It now becomes obvious that the function body has no way of knowing what N is.

However, if a function expects an array reference, then the compiler does make sure that the size of the actual parameter matches the declaration. This means we can make definition 2 work with a minor modification (definition 3):

template <typename T, size_t N>
size_t countof( T (&array)[N] )
{
    return N;
}

This countof works very well and you cannot fool it by giving it a pointer. However, it is a function, not a macro. This means you cannot use it where a compile time constant is expected. In particular, you cannot write something like:

int x[10];

int y[ 2*countof(x) ]; // twice as big as x

Can we do anything about it?

Someone (I don’t know who it is – I just saw it in a piece of code from an unknown author) came up with a clever idea: moving N from the body of the function to the return type (e.g. make the function return an array of N elements), then we can get the value of N without actually calling the function.

To be precise, we have to make the function return an array reference, as C++ does not allow you to return an array directly.

The implementation of this is:

template <typename T, size_t N>
char ( &_ArraySizeHelper( T (&array)[N] ))[N];

#define countof( array ) (sizeof( _ArraySizeHelper( array ) ))

Admittedly, the syntax looks awful. Indeed, some explanation is necessary.

First, the top-level stuff

char ( &_ArraySizeHelper( ... ))[N];

says _ArraySizeHelper is a function that returns a reference (note the &) to a char array of N elements.

Next, the function parameter is

T (&array)[N]

which is a reference to a T array of N elements.

Finally, countof is defined as the size of the result of the function _ArraySizeHelper. Note we don’t even need to define _ArraySizeHelper(), — a declaration is enough.

With this new definition,

int x[10];

int y[ 2*countof(x) ]; // twice as big as x

becomes valid, just as we desire.

Am I happy now? Well, I think this definition is definitely better than the others we have visited, but it is still not quite what I want. For one thing, it doesn’t work with types defined inside a function. That’s because the template function _ArraySizeHelper expects a type that is accessible in the global scope.

I don’t have a better solution. If you know one, please let me know.

This is pretty much old and legendary question and there are already many amazing answers out there. But with time there are new functionalities being added to the languages, so we need to keep on updating things as per new features available.

I just noticed any one hasn’t mentioned about C++20 yet. So thought to write answer.

C++20

In C++20, there is a new better way added to the standard library for finding the length of array i.e. std:ssize(). This function returns a signed value.

#include <iostream>

int main() {
    int arr[] = {1, 2, 3};
    std::cout << std::ssize(arr);
    return 0;
}

C++17

In C++17 there was a better way (at that time) for the same which is std::size() defined in iterator.

#include <iostream>
#include <iterator> // required for std::size

int main(){
    int arr[] = {1, 2, 3};
    std::cout << "Size is " << std::size(arr);
    return 0;
}

P.S. This method works for vector as well.

Old

This traditional approach is already mentioned in many other answers.

#include <iostream>

int main() {
    int array[] = { 1, 2, 3 };
    std::cout << sizeof(array) / sizeof(array[0]);
    return 0;
}

Just FYI, if you wonder why this approach doesn’t work when array is passed to another function. The reason is,

An array is not passed by value in C++, instead the pointer to array is passed. As in some cases passing the whole arrays can be expensive operation. You can test this by passing the array to some function and make some changes to array there and then print the array in main again. You’ll get updated results.

And as you would already know, the sizeof() function gives the number of bytes, so in other function it’ll return the number of bytes allocated for the pointer rather than the whole array. So this approach doesn’t work.

But I’m sure you can find a good way to do this, as per your requirement.

Happy Coding.

В этой статье мы рассмотрим, как определить количество элементов в объекте Python и при необходимости подсчитать их сумму. Также увидим, как подсчитать количество вхождений конкретного элемента.

Python_Pro_970x90-20219-1c8674.png

Итак, представим, что у нас есть следующий массив:


По условию задачи мы хотим определить, сколько элементов в данном массиве, и какова сумма всех этих элементов.

В первую очередь, вспомним, что в языке программирования Python существует специальная функция, возвращающая длину списка, массива, последовательности и так далее — это len(x), где x — наша последовательность.

Если разобраться, длина последовательности из чисел — это одновременно и количество самих цифр, поэтому мы можем решить поставленную задачу следующим образом:

print(len(array))
6
Press any key to continue . . .

А для подсчёта суммы можем занести перечисление массива Python в цикл:

array = [6,2,7,4,8,1]
sum = 0
for i in range(len(array)):
    sum  = array[i]
print(sum)

В принципе, вопрос решён. Но, по правде говоря, перебор целочисленного массива с помощью цикла для получения суммы элементов массива — это, всё же, костыль)). Дело в том, что в Python существует встроенная функция sum(). Она вернёт нам сумму без лишних телодвижений.

def main():
    array = [1,6,3,8,4,9,25,2]
    print(sum(array))
if name == 'main':

main()
58
Press any key to continue . . .

Python: количество вхождений конкретного элемента

Бывает, нам надо подсчитать число вхождений определённых элементов в списке и вернуть найденное значение. Для этого в Python есть метод count(). Вот его синтаксис:


Метод принимает аргумент x, значение которого нас интересует. И возвращает число вхождений интересующего элемента в список:

# объявляем список
website_list = ['otus.ru','includehelp.com', 'yandex.by', 'otus.ru']

# подсчитываем вхождения 'otus.ru'
count = website_list.count('otus.ru')
print('otus.ru found',count,'times.')

# подсчитываем вхождения 'yandex.by'
count = website_list.count('yandex.by')
print('yandex.by found',count,'times.')

Итог будет следующим:

otus.ru found 2 times.
yandex.by found 1 times.

Также этот метод успешно работает и с кортежами:

# объявляем кортеж
sample_tuple = ((1,3), (2,4), (4,6))

# условные вхождения (1,2) 
count = sample_tuple.count((1,2))
print('(1,2) found',count,'times.')

# условные вхождения (1,3) 
count = sample_tuple.count((1,3))
print('(1,3) found',count,'times.')

Результат:

(1,2) found 0 times.
(1,3) found 1 times.

Вот и всё, теперь вы знаете, как подсчитывать количество элементов в списке, массиве, кортеже в Python.

Python_Pro_970x550-20219-0846c7.png

count

(PHP 4, PHP 5, PHP 7)

countПодсчитывает количество элементов массива или что-то в объекте

Описание

int count
( mixed $array_or_countable
[, int $mode = COUNT_NORMAL
] )

Для объектов, если у вас включена поддержка
SPL, вы можете перехватить
count(), реализуя интерфейс
Countable. Этот интерфейс имеет ровно один метод,
Countable::count(), который возвращает значение функции
count().

Пожалуйста, смотрите раздел
«Массивы» в этом
руководстве для более детального представления о
реализации и использовании массивов в PHP.

Список параметров

array_or_countable

Массив или Countable объект.

mode

Если необязательный параметр mode установлен в
COUNT_RECURSIVE (или 1), count()
будет рекурсивно подсчитывать количество элементов массива.
Это особенно полезно для подсчёта всех элементов многомерных
массивов.

Предостережение

count() умеет определять рекурсию для избежания
бесконечного цикла, но при каждом обнаружении выводит ошибку уровня
E_WARNING (в случае, если массив содержит себя
более одного раза) и возвращает большее количество, чем могло бы
ожидаться.

Возвращаемые значения

Возвращает количество элементов в array_or_countable.
Если параметр не является массивом или объектом,
реализующим интерфейс Countable,
будет возвращена 1.
За одним исключением: если array_or_countableNULL,
то будет возвращён 0.

Предостережение

count() может возвратить 0 для переменных, которые
не установлены, но также может возвратить 0 для переменных, которые
инициализированы пустым массивом. Используйте функцию
isset() для того, чтобы протестировать, установлена ли переменная.

Примеры

Пример #1 Пример использования count()


<?php
$a
[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result count($a);
// $result == 3$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
$result count($b);
// $result == 3$result count(null);
// $result == 0$result count(false);
// $result == 1
?>

Пример #2 Пример рекурсивного использования count()


<?php
$food 
= array('fruits' => array('orange''banana''apple'),
              
'veggie' => array('carrot''collard''pea'));// рекурсивный count
echo count($foodCOUNT_RECURSIVE); // выводит 8

// обычный count

echo count($food); // выводит 2?>

Смотрите также

  • is_array() — Определяет, является ли переменная массивом
  • isset() — Определяет, была ли установлена переменная значением отличным от NULL
  • strlen() — Возвращает длину строки

Вернуться к: Функции для работы с массивами

Понравилась статья? Поделить с друзьями:
  • Как найти наименьшее кратное число двух чисел
  • Как найти свой почтовый ящик на майл
  • Как найти поставщика для своего магазина одежды
  • Как найти батарею в fallout 4
  • Как найти пароль от виртуальной школы