How many times a value is on an array using php

This is a very simple function, but ver useful. Enjoy it!

 
function getRepetitions($value, array $values){
	$length = count($values);
	if($length==0)
		return FALSE;
	$repetitions = 0;
	foreach($values as $v){
		if($v==$value)
			$repetitions++;
	}
	return $repetitions;
}
print getRepetitions(3,array(3,3,3,5,6,4,3,6,5,4,6,3,2,8,8))."\n";
 
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
Leave a comment

1 Comments.

  1. Interesting, but here you have another way to do the same…
    function getRepetitions($value, array $values){
    if(!sizeof($values))
    return false;
    foreach($values as $v){
    $rep[$v]++;
    }
    return (int)$rep[$value];
    }
    print getRepetitions(3,array(3,3,3,5,6,4,3,6,5,4,6,3,2,8,8)).”\n”;

Leave a Reply


[ Ctrl + Enter ]