посчитать количество одинаковых элементов в массиве 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.

Источник

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

Содержание

User Contributed Notes 14 notes

A simple trick that can help you to guess what diff/intersect or sort function does by name.

Example: array_diff_assoc, array_intersect_assoc.

Example: array_diff_key, array_intersect_key.

Example: array_diff, array_intersect.

Example: array_udiff_uassoc, array_uintersect_assoc.

This also works with array sort functions:

Example: arsort, asort.

Example: uksort, ksort.

Example: rsort, krsort.

Example: usort, uasort.

?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>

Updated code of ‘indioeuropeo’ with option to input string-based keys.

Here is a function to find out the maximum depth of a multidimensional array.

// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)

Short function for making a recursive array copy while cloning objects on the way.

If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:

to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.

to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);

You can also stringify objects, numbers, etc.

Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:

I was looking for an array aggregation function here and ended up writing this one.

Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.

While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.

Источник

Посчитать количество одинаковых элементов в массиве

Всем привет, есть массив вида:

Добавлено через 19 минут
Решено:
$count = array_count_values(array_column($breakfest, ‘PROPERTY_BLUDO_VALUE’));

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

Посчитать количество определенных элементов в массиве
В общем есть многомерный массив такого вида Нужно перебрать его так, чтобы в конце иметь понятие.

посчитать количество одинаковых элементов в массиве php. Смотреть фото посчитать количество одинаковых элементов в массиве php. Смотреть картинку посчитать количество одинаковых элементов в массиве php. Картинка про посчитать количество одинаковых элементов в массиве php. Фото посчитать количество одинаковых элементов в массиве phpПосчитать количество одинаковых чисел в массиве
Беда такая, не могу посчитать количество одинаковых элементов в массиве, всегда получается 0, код.

Посчитать количество одинаковых элементов
Есть, например, строка ((2 3) J K(3 K) J) и результат будет мол три атома повторяются 2 раза.

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

Посчитать количество одинаковых элементов(матрица)
Можете пожалуйста дополнить предыдущие задание Посчитать количество одинаковых элементов, но уже.

посчитать количество одинаковых элементов в массиве php. Смотреть фото посчитать количество одинаковых элементов в массиве php. Смотреть картинку посчитать количество одинаковых элементов в массиве php. Картинка про посчитать количество одинаковых элементов в массиве php. Фото посчитать количество одинаковых элементов в массиве phpПосчитать количество одинаковых подряд стоящих элементов
Здравствуйте! Есть такое задание. Дан массив. Найти количество одинаковых подряд стоящих.

посчитать количество одинаковых элементов в массиве php. Смотреть фото посчитать количество одинаковых элементов в массиве php. Смотреть картинку посчитать количество одинаковых элементов в массиве php. Картинка про посчитать количество одинаковых элементов в массиве php. Фото посчитать количество одинаковых элементов в массиве phpПосчитать количество одинаковых элементов в двух массивах
#include #include #include using namespace std; map a;.

Необходимо посчитать количество подряд идущих одинаковых элементов
есть массив, состоящий из 0 и 1 нужно посчитать наибольшее количество подряд идущих одинаковых.

Найти количество одинаковых элементов в массиве из 8 или более элементов
Дан произвольный массив из более чем 7ми элементов. Нужно найти количество одинаковых пар.

Источник

array_unique

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_unique — Убирает повторяющиеся значения из массива

Описание

Принимает входной массив array и возвращает новый массив без повторяющихся значений.

Обратите внимание, что ключи сохранятся. Если в соответствии с заданными flags несколько элементов определяются как идентичные, то будут сохранены ключ и значение первого такого элемента.

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

Можно использовать необязательный второй параметр flags для изменения поведения сортировки с помощью следующих значений:

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

Возвращает отфильтрованный массив.

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

Примеры

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

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

Пример #2 array_unique() и типы:

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

Примечания

Замечание: Обратите внимание, что array_unique() не предназначена для работы с многомерными массивами.

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

User Contributed Notes 41 notes

Create multidimensional array unique for any single key index.
e.g I want to create multi dimentional unique array for specific code

Code :
My array is like this,

In reply to performance tests array_unique vs foreach.

In PHP7 there were significant changes to Packed and Immutable arrays resulting in the performance difference to drop considerably. Here is the same test on php7.1 here;
http://sandbox.onlinephpfunctions.com/code/2a9e986690ef8505490489581c1c0e70f20d26d1

$max = 770000; //large enough number within memory allocation
$arr = range(1,$max,3);
$arr2 = range(1,$max,2);
$arr = array_merge($arr,$arr2);

I find it odd that there is no version of this function which allows you to use a comparator callable in order to determine items equality (like array_udiff and array_uintersect). So, here’s my version for you:

$array_of_objects = [new Foo ( 2 ), new Foo ( 1 ), new Foo ( 3 ), new Foo ( 2 ), new Foo ( 2 ), new Foo ( 1 )];

It’s often faster to use a foreache and array_keys than array_unique:

For people looking at the flip flip method for getting unique values in a simple array. This is the absolute fastest method:

This tested on several different machines with 100000 random arrays. All machines used a version of PHP5.

I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:

$raw_array = array();
$raw_array [ 1 ] = ‘abc@xyz.com’ ;
$raw_array [ 2 ] = ‘def@xyz.com’ ;
$raw_array [ 3 ] = ‘ghi@xyz.com’ ;
$raw_array [ 4 ] = ‘abc@xyz.com’ ; // Duplicate

Case insensitive; will keep first encountered value.

Simple and clean way to get duplicate entries removed from a multidimensional array.

Taking the advantage of array_unique, here is a simple function to check if an array has duplicate values.

It simply compares the number of elements between the original array and the array_uniqued array.

The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value:

If you find the need to get a sorted array without it preserving the keys, use this code which has worked for me:

?>

The above code returns an array which is both unique and sorted from zero.

recursive array unique for multiarrays

This is a script for multi_dimensional arrays

My object unique function:

another method to get unique values is :

?>

Have fun tweaking this ;)) i know you will ;))

From Romania With Love

Another form to make an array unique (manual):

Array
(
[0] => Array
(
[0] => 40665
[1] => 40665
[2] => 40665
[3] => 40665
[4] => 40666
[5] => 40666
[6] => 40666
[7] => 40666
[8] => 40667
[9] => 40667
[10] => 40667
[11] => 40667
[12] => 40667
[13] => 40668
[14] => 40668
[15] => 40668
[16] => 40668
[17] => 40668
[18] => 40669
[19] => 40669
[20] => 40670
[21] => 40670
[22] => 40670
[23] => 40670
[24] => 40671
[25] => 40671
[26] => 40671
[27] => 40671
[28] => 40671
)

[1] => Array
(
[0] => 40672
[1] => 40672
[2] => 40672
[3] => 40672
)

0
0 => 40665
4 => 40666
8 => 40667
13 => 40668
18 => 40669
20 => 40670
24 => 40671

saludos desde chile.

[Editor’s note: please note that this will not work well with non-scalar values in the array. Array keys can not be arrays themselves, nor streams, resources, etc. Flipping the array causes a change in key-name]

You can do a super fast version of array_unique directly in PHP, even faster than the other solution posted in the comments!

Compared to the built in function it is 20x faster! (2x faster than the solution in the comments).

I found the simplest way to «unique» multidimensional arrays as follows:

?>

As you can see «b» will be removed without any errors or notices.

Here’s the shortest line of code I could find/create to remove all duplicate entries from an array and then reindex the keys.

I searched how to show only the de-duplicate elements from array, but failed.
Here is my solution:

Problem:
I have loaded an array with the results of a database
query. The Fields are ‘FirstName’ and ‘LastName’.

I would like to find a way to contactenate the two
fields, and then return only unique values for the
array. For example, if the database query returns
three instances of a record with the FirstName John
and the LastName Smith in two distinct fields, I would
like to build a new array that would contain all the
original fields, but with John Smith in it only once.
Thanks for: Colin Campbell

Another way to ‘unique column’ an array, in this case an array of objects:
Keep the desired unique column values in a static array inside the callback function for array_filter.

Lets say that you want to capture unique values from multidimensional arrays and flatten them in 0 depth.

I hope that the function will help someone

# move to the next node
continue;

# increment depth level
$l ++;

Источник

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;

Источник

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

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