I need to get one time occurence on my array, with my code I get only first result here is my example code:
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
if($arrs[$arr[$i]]==1)
{
//do something...in this example i expect to receive b c and d
}
}
Thanks in advance
ciao h
-
What do you mean by "get" and "receive"? What do you want to do with the result?Lightness Races in Orbit– Lightness Races in Orbit2011年04月12日 12:49:10 +00:00Commented Apr 12, 2011 at 12:49
-
I mean same thing excuse me my English is really poor..haltman– haltman2011年04月12日 12:57:56 +00:00Commented Apr 12, 2011 at 12:57
-
"Same thing"? I am asking what you want to do with the result.Lightness Races in Orbit– Lightness Races in Orbit2011年04月12日 13:07:06 +00:00Commented Apr 12, 2011 at 13:07
-
@Tomalak: I use them to exclude values from filering conditions..haltman– haltman2011年04月12日 13:17:09 +00:00Commented Apr 12, 2011 at 13:17
-
We need more specific information. Can you expand on your code example? What does "do something" mean?Lightness Races in Orbit– Lightness Races in Orbit2011年04月12日 13:19:00 +00:00Commented Apr 12, 2011 at 13:19
5 Answers 5
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
if($arrs[$arr[$i]]==1)
{
echo $arr[$i];
}
}
That should display bcd
$arr=array("a","a","b","c","d");
$result = array();
$doubles = array();
while( !empty( $arr ) ) {
$value = array_pop( $arr );
if( !in_array( $value, $arr )
&& !in_array( $value, $doubles ) ) {
$result[] = $value;
}
else {
$doubles[] = $value;
}
}
4 Comments
May be you've miss your real results:
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
/*
now $arrs is:
array (
'a' => 2,
'b' => 1,
'c' => 1,
'd' => 1,
)
*/
foreach($arrs as $id => $count){
if($count==1) {
// do your code
}
}
/*******************************************************/
/* usefull version */
/*******************************************************/
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
foreach($arr as $id ){
if($arrs[$id]==1){
// do your code
echo "$id is single\n";
}
}
1 Comment
You just need to retrieve any value which only occurs once in the array, right? Try this:
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
foreach ($arrs as $uniqueValue => $count)
{
if($value == 1) {
echo $uniqueValue;
}
}
array_count_values returns an associative array where the key is the value found and its value is the number of times it occurs in the original array. This loop simply iterates over each unique value found in your array (i.e. the keys from array_count_values) and checks if it was only found once (i.e. that key has a value of 1). If it does, it echos out the value. Of course, you probably want to do something a bit more complex with the value, but this works as a placeholder.
Comments
$count = 0;
foreach(array("a","a","b","c","d") as $v){
if($v == 1){$count++;}
}