Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variable exist more than once in array?

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

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

like image 302
Donavon Yelton Avatar asked Jan 16 '12 16:01

Donavon Yelton


2 Answers

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

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 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 this http://www.php.net/manual/en/function.array-keys.php - "If the optional search_value is specified, then only the keys for that value are returned"

like image 192
Ninja Avatar answered Sep 18 '22 20:09

Ninja


Take a look at array_count_values().

like image 43
CodeCaster Avatar answered Sep 18 '22 20:09

CodeCaster