Like as always we have a problem we have some prerequisites we will have a function and we will draw some results
Problem and Prerequisites :
We have an array let us suppose array(1,2,1,3,4,5,4,6,3,2,1,2,8,9,3,4,5,3,2,4,6,2) and we want to create a function that checks for number of times value repeats in the array.
So we need and output like
1 repeats 3 times
2 repeats 5 times etc.
Function and Solution :
Output:
1 repeats 3 times
2 repeats 5 times
3 repeats 4 times
4 repeats 4 times
5 repeats 2 times
6 repeats 2 times
8 repeats 1 times
9 repeats 1 times
Problem and Prerequisites :
We have an array let us suppose array(1,2,1,3,4,5,4,6,3,2,1,2,8,9,3,4,5,3,2,4,6,2) and we want to create a function that checks for number of times value repeats in the array.
So we need and output like
1 repeats 3 times
2 repeats 5 times etc.
Function and Solution :
<?php
function get_modes($numarray)
{
if(!(is_array($numarray)))
throw new Exception ('Parameter Not an array');
$revarray=array();
foreach($numarray as $key=>$value)
{
if(array_key_exists($value,$revarray))
{
$revarray[$value]++;
}
else
{
$revarray[$value]=1;
}
}
return $revarray;
}
$myarray=array(1,2,1,3,4,5,4,6,3,2,1,2,8,9,3,4,5,3,2,4,6,2);
$navarray=get_modes($myarray);
foreach($navarray as $key=>$value)
{
echo $key." repeats ".$value." times<br/>";
}
?>
Output:
1 repeats 3 times
2 repeats 5 times
3 repeats 4 times
4 repeats 4 times
5 repeats 2 times
6 repeats 2 times
8 repeats 1 times
9 repeats 1 times
No comments:
Post a Comment