Count occurrences of value in array, return values once


/ Published in: PHP
Save to your folder(s)

I needed to trim a simple numerical array that might have duplicate values into an array with no duplicates. I came up with this before finding array_unique(). D\'oh.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. $array = array(1,1,1,2,2,2,2,3);
  4.  
  5. function returnValueOnce($array){
  6.  
  7. $arrayTrim = array_keys(array_count_values($array));
  8. //array_count_values returns an array( [1]=>3 [2]=> 4 [3]=> 1 )
  9.  
  10. return $arrayTrim;
  11. //returns numerical array(1,2,3)
  12. }
  13. // the array_unique() function does this too, so now I'm the wiser....
  14.  
  15. // it removes duplicate values from an array. If two or more array values are the same, the // first appearance will be kept and the other will be removed.
  16. ?>

URL: http://www.w3schools.com/php/func_array_unique.asp

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.