-
Hi all,
I have just finished a small job only to realise that the client has PHP3 not 4! running, everything works except
array_count_values() - which is PHP4 only, I am certain I saw somewhere here a php version of this - ie a script which does the same job, I have searched but can not find it.. anybody?
I guess I can work it out but agggghhh my head hurts , I basically need to return an array that holds the values and frequency of another array.
-
It is a piece of cake to cut your own function to do this:
PHP Code:
function array_count_values ($array) {
$countValues = array();
while( list($key, $val) = each($array) ) {
++$countValues[$val];
}
return $countValues;
}
Note I was going to use the conditional foreach to loop through the array but checked that it was php3 which it is not.
-
Thanks Freakysid but that does not work for me (unless I implemented it incorrectly?), I need an array that includes the array value and the number of times it occurs, I have gotten around it using this.
Code:
function my_count_values($temp){global $thisname;
$rets=0;
while(list($key,$var)=each($thisname)){
if ($temp==$var){$rets++;}}
return $rets;
}
while(list($key,$var)=each($althisname)){
$rets=my_count_values($var);
if($rets>1){$temparray[$var]=1;}
reset($thisname);
}
& while it works it also sucks :) - if you have an array with 400 values (which I do) this checks each value (400) 400 times!
This application is unlikely to ever have to cope with more than that ,but I hate code which I know is innefficient.
Cheers.
note that $thisname and $althisname are copies of each other
-
Test Code:
PHP Code:
<?php
function my_array_count_values($array) {
$countVals = array();
while(list($key, $val) = each($array)) {
$countVals[$val]++;
}
return $countVals;
}
$values = array("hat", "pipe", "trout", "fig", "pipe", "hat", "aardvark",
"moustache", "pipe", "dog", "pipe", "fig", "fig");
$frequencies = my_array_count_values($values);
while(list($key, $val) = each($frequencies)) {
echo "$key $val <br>";
}
?>
Results:
hat 2
pipe 4
trout 1
fig 3
aardvark 1
moustache 1
dog 1
:)