1. ## Array Help

I need to be able to determine if an integer occurs more than once in an array.

So with the following array if we tested 9 then it would return false.

PHP Code:
``` \$test = array(5, 5, 5, 2, 2, 5, 6, 6, 9);  ```
What is the best way to do this?

Thanks

2. Here's one way, someone may have a better way:
PHP Code:
``` function has_duplicates(\$array, \$value) {     \$count = array_count_values(\$array);     return (\$count[\$value] >1) ? true : false; } \$test = array(5, 5, 5, 2, 2, 5, 6, 6, 9);  if (has_duplicates(\$test,9)) {     echo "duplicates found!"; } else {     echo "no duplicates found!"; }  ```

4. Longer and possibly less efficient solution. Sorry, I'm bored

PHP Code:
``` function hasDuplicates(\$array, \$item) {     \$count = 0;     foreach (\$array as \$value) {         if (\$count > 1) {             return true;         }         else if (\$value == \$item) {             \$count++;         }     }     if (\$count > 1) {         return true;     } else {         return false;     } } \$test = array(5, 5, 5, 2, 2, 5, 6, 9, 9);  echo (hasDuplicates(\$test, 6)) ? 'has duplicates' : 'no duplicates';  ```

5. Another way to do it using array_unique.

PHP Code:
``` \$test = array(5, 5, 5, 2, 2, 5, 6, 6, 9); \$test_unique = array_unique(\$test); if (count(\$test) == count(\$test_unique)) {   print 'There are no duplicates.'; } else {   print 'There are duplicates.'; }  ```

6. Another option would be to use array_keys with the optional \$search_value argument.

has_duplicates function using array_keys
PHP Code:
``` // Returns TRUE when \$value appears in \$array // more than once, FALSE otherwise. // Note: Use optional third argument (\$strict) //       to force type check on the \$value. function has_duplicates(\$array, \$value, \$strict = TRUE) {     return (bool) (count(array_keys(\$array, \$value, \$strict)) > 1); }  ```

7. Salathe, why the unnecesary boolean cast and parenthesis? For self documentation/clarity?

8. Originally Posted by crmalibu
Salathe, why the unnecesary boolean cast and parenthesis? For self documentation/clarity?
I often write return (bool) just so it is completely clear at-a-glance: especially in this kind of case where the line starts with return count otherwise.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•