Check if a variable exists in the array more than once?

I want to make an if / else statement in PHP that relies on an element in an array that exists more than once or not. Can you use count in in_array? do something like:

if (count(in_array($itemno_array))) > 1 { EXECUTE CODE }

+6
source share
4 answers

Let $ item be the element whose frequency you are checking in the array, $ array the array you are looking for.

SOLUTION 1:

 $array_count = array_count_values($array); if (array_key_exists($item, $array_count) && ($array_count["$item"] > 1)) { /* Execute code */ } 

array_count_values โ€‹โ€‹() returns an array using the values โ€‹โ€‹of the input array as keys and their frequency in the input as values โ€‹โ€‹( http://php.net/manual/en/function.array-count-values.php )

SOLUTION 2:

 if (count(array_keys($array, $item)) > 1) { /* Execute code */ } 

Check http://www.php.net/manual/en/function.array-keys.php - "If the search_value option is specified, only keys for this value are returned"

+8
source

Take a look at array_count_values() .

+4
source

http://www.php.net/manual/en/function.array-keys.php

in_array returns bool, so you cannot read it. array_keys, however, returns an array of all the keys for the element in the array, so checking the length of this result will give you whether it exists more than once or not.

+3
source

Maybe I misunderstood your question, but maybe this is what you did:

 if ( count($in_array) > count(array_unique($in_array)) ) { EXECUTE CODE } 
+1
source

Source: https://habr.com/ru/post/906130/


All Articles