开发者

Inserting only unique values into an array

I have a set of values that I'm pushing into an array in the order t开发者_StackOverflow社区hey occur

$valsArray = array(); 

//I process each value from a file (code removed for simplicity) 
//and then add into the array 
$valsArray[] = $val; 

How do I turn this into an associative array instead where the value gets inserted (as $key of associative array) only if it doesn't exist. If it does exist increment its count ($value of associative array) by 1. I'm trying to find a more efficient way of handling those values compared to what I'm doing now.


$valsArray = array_unique($valsArray);


As you loop thru your values you can do the following:

isset( $valsArray[$val] ) ? $valsArray[$val]++ : $valsArray[$val]=1;

example:

$valsArray=array();

$val="foo";
isset($valsArray[$val])?$valsArray[$val]++:$valsArray[$val]=1;
$val="foo";
isset($valsArray[$val])?$valsArray[$val]++:$valsArray[$val]=1;
$val="bar";
isset($valsArray[$val])?$valsArray[$val]++:$valsArray[$val]=1;

print_r($valsArray);

will get you:

Array ( [foo] => 2 [bar] => 1 ) 


@$valsArray[$val]++;

should do it for you. New entries get added as a key with a value of 1, existing entries get their value incremented. The @ avoids an E_NOTICE being thrown every time this encounters a new value.


Can't you just $valsArray = array_unique($valsArray); when you're done adding? Or do you need to keep the keys in correct order?


Trying looking at the following documentation

http://www.php.net/manual/en/function.array-count-values.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜