count array elements php

array_count_values

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

array_count_values — Подсчитывает количество всех значений массива

Описание

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

Массив подсчитываемых значений

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

Возвращает ассоциативный массив со значениями array в качестве ключей и их количества в качестве значений.

Ошибки

Генерирует ошибку уровня E_WARNING для каждого элемента, не являющегося строкой ( string ) или целым числом ( int ).

Примеры

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

Результат выполнения данного примера:

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

User Contributed Notes 15 notes

Simple way to find number of items with specific values in multidimensional array:

Based on sergolucky96 suggestion
Simple way to find number of items with specific *boolean* values in multidimensional array:

The case-insensitive version:

I couldn’t find a function for counting the values with case-insensitive matching, so I wrote a quick and dirty solution myself:

Array
(
[J. Karjalainen] => 3
[60] => 2
[j. karjalainen] => 1
[Fastway] => 2
[FASTWAY] => 1
[fastway] => 1
[YUP] => 1
)
Array
(
[J. Karjalainen] => 4
[60] => 2
[Fastway] => 4
[YUP] => 1
)

I don’t know how efficient it is, but it seems to work. Needed this function in one of my scripts and thought I would share it.

I find a very simple solution to count values in multidimentional arrays (example for 2 levels) :

Yet Another case-insensitive version of array_count_values()

Array
(
[j. karjalainen] => 4
[60] => 2
[fastway] => 4
[yup] => 1
)

byron at byronrode dot co dot za, here are some benchmarks.

__array_keys()__
Count:515
Time:0.0869138240814
Memory:33016

__$needle_array[]__
Count:515
Time:0.259949922562
Memory:24792

__$number_of_instances++__
Count:515
Time:0.258481025696
Memory:0

However, when you use an array of strings by calling md5(rand(1, 2000)), the performance boosts become less significant:

__array_count_values()__
Count:499
Time:0.491794109344
Memory:184328

__array_keys()__
Count:499
Time:0.36399102211
Memory:30072

__$needle_array[]__
Count:499
Time:0.568728923798
Memory:22104

__$number_of_instances++__
Count:499
Time:0.574353933334
Memory:0

Results are similar for string->string haystacks with foreach traversal.

Источник

count

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

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

Описание

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

Смотрите раздел Массивы в этом руководстве для более детального представления о реализации и использовании массивов в PHP.

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

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

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

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

Список изменений

Примеры

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

Результат выполнения данного примера:

var_dump ( count ( null ));

var_dump ( count ( false ));
?>

Результат выполнения данного примера:

Результат выполнения данного примера в PHP 7.2:

Результат выполнения данного примера в PHP 8:

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

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

User Contributed Notes 17 notes

[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 are on PHP 7.2+, you need to be aware of «Changelog» and use something like this:

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

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.

$arr [ ‘__been_here’ ] = true ;

to end the debate: count() is the same as empty()

results on my computer:

count : double(0.81396999359131)
empty : double(0.81621310710907)

using isset($test[0]) is a bit slower than empty;
test without adding value to the array in function ****Test: still the same.

A function of one line to find the number of elements that are not arrays, recursively :

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

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

For a Non Countable Objects

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..

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

To get the count of the inner array you can do something like:

$inner_count = count($array[0]);
echo ($inner_count);

About 2d arrays, you have many way to count elements :

Criada para contar quantos níveis um array multidimensional possui.

/* Verifica se o ARRAY foi instanciado */
if (is_setVar($matrix))<

/* Verifica se a variável é um ARRAY */
if(is_array($matrix))<

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.

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

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

Источник

Count elements in adjacent array

I want to loop through that array and store some information for each level in another array. This is how my array should look like at the end.

E.g. this shows that at level 0 are 3 nodes and at level 1 there are 5 nodes. How can I do that? Any ideas?

count array elements php

3 Answers 3

I would just count the numbers.

This means each item of the base key plus the same for it’s children.

In opposite to recursion, I decided to use a stack for this.

To have a value per level, the counter needs a level context as well, which is added to the stack next to the node:

Edit: Storing the nodes

Discussion

Using a stack prevents to make recursion function calls and reduces complexity. The idea behind it is fairly simple:

Comparing Stack to Recursion Function Stack

Comparing using an own stack to the PHP’s function stack first of all shows that both ways have things in common. Both make use of a stack.

But the main difference is, that an own stack prevents using the function calls. Calling a function, especially recursively has multiple implications that can be avoided.

Another key difference is, that an own stack always allows to interrogate with it while there is no control over the PHP language’s own stack.

Next to that, an own stack can be processed sequentially, while the function stack is a recursive construct that maps the processing of the data 1:1 into the program flow.

While recursion will hide away the recursive nature of the data (tree) for the code within the function (which can simplify processing), there is the need to offer the state that gets hidden away by function calls to be introduced as function parameters.

Managing the data to solve the problem therefore is not less but equal or more complex with recursion.

So next to the overhead of the function calls, one can already smell an overhead for data.

It’s worth to see this in the light of the PHP language itself.

To make recursion work, PHP needs to add additional variable tables onto the function stack. These tables need to be managed before and after each function call.

The recursion also needs you to pass variables by references. This is an additional overhead, as those values need to be set/processed before and after the function ends by PHP.

Such a reference is needed in the recursion to share the data structure for the counter. This overhead in a recursive implementation could be reduced by implementing the recursion into a class of it’s own in PHP, which has not been suggested so far and is probably worth to consider.

Like the counter array in a user stack implementation, such a class could share the counter between all function calls, providing a hash accessible to the class’s member function(s) w/o making use of variable references. Further on, complexity in solving the problem can be distributed over different functions with in the class or even injected as a dependency. PHP offers a default recursive iterator interface already.

Recursive Implementation by Class

This is a recursive implementation based on the idea raised in the discussion above to get more grip on it:

Источник

Counting PHP Array Elements Using count()

count array elements php

Often it’s useful to know how many elements an array contains. Here are some common reasons for counting the number of elements in an array:

PHP makes it easy to count array elements, thanks to its built-in count() function. In this tutorial you’ll learn how to use count() to count the elements in both regular and multidimensional arrays, and how to move through all the elements of an indexed array by using count() and a for loop.

Basic count() usage

Using count() is easy. Just pass it the array whose elements you want to count, and the function returns the number of elements in the array:

The above example counts the elements in an indexed array, but you can just as easily count an associative array:

Moving through arrays with count() and for loops

What’s happening here? The above example is identical to the one before, except that the array indices are no longer contiguous (0, 1, 2, and 39). We’ve also set PHP to display all errors in the browser. When the code tries to read the element with the index of 3, PHP generates an “Undefined offset” notice because an element with this index doesn’t exist.

If you’re not sure whether the indices of an array are contiguous, you can use other PHP constructs such as foreach to loop through the array’s elements. (More on foreach in a later tutorial.)

Counting multidimensional arrays

We touched briefly on multidimensional arrays in Creating Arrays in PHP. Essentially, a multidimensional array is an array whose elements are also arrays.

By default, count() only counts the elements in the top level of a multidimensional array. Here’s an example:

The above code only counts the 2 elements in the top-level array ( «directors» and «movies» ).

If you want to count all the elements in a multidimensional array — that is, not just the top-level elements, but the elements in all arrays inside the array — then pass the constant COUNT_RECURSIVE as a second argument to count() :

Summary

In this tutorial, you’ve explored PHP’s count() function for counting the number of elements in an array. You’ve also learned:

Reader Interactions

Leave a Reply Cancel reply

Primary Sidebar

Hire Matt!

count array elements php

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

count array elements php

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Источник

How can I count the number of element inside an array with value equals a constant? example,

how can I directly know how many «Ben» is inside?

count array elements php

count array elements php

10 Answers 10

You can do this with array_keys and count.

To count a value in a two dimensional array, here is the useful snippet to process and get count of a particular value

count array elements php

try the array_count_values() function

If you want to count ALL the same occurences inside the array, here’s a function to count them all, and return the results as a multi-dimensional array:

array_count_values only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:

Not the answer you’re looking for? Browse other questions tagged php arrays count or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *