9

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 }

3 Answers 3

11

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"

Sign up to request clarification or add additional context in comments.

2 Comments

You might like to cater for the instance where $item does not exist in $array.
I have edited and added another solution too. You may check it out.
3

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

in_array only returns a bool, so you can't count it. array_keys however returns an array of all keys for an item in the array, so checking the length of that result will give you whether it exists more than once or not.

2 Comments

This will not work in all cases. What if the item that repeats is not the one he is looking for?
Sorry, I misunderstood what Gordon told. My bad. Realized he is talking about the search value parameter in array_keys function
1

I may have misunderstood your question but maybe this is what you neeed:

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

1 Comment

This is incorrect. What if the item that repeats is not the one he is looking for?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.