views:

197

answers:

4

I have a set of values that I'm pushing into an array in the order they 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.

A: 

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

Aal
They don't need to be in correct order so that's one way. But if I do it this way, I lose information about their count (e.g. `orange` was answered 5 times, or `apple` was chosen as an answer 15 times). With an associative array, it's possible to store their count as the `$value` of the `$key`
karl
+3  A: 
@$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.

Sparr
Will generate E_NOTICE level errors when the element doesn't yet exist.
chris
@chris Unfortunately that's true, although it's a very good answer and came first before zaf's. I think for future readers with the same question, I'll choose zaf's answer since it's more complete.
karl
Ahh, I didn't realize it generated an error. Drat. Thanks for pointing that out. I would edit to something like zaf's but he already did that nicely so I'll leave mine as an example of the shorter less-nice way to do it.
Sparr
Added the @ to make it cleaner :)
Sparr
@Sparr, I'm curious now, which is better practice? Does the `@` just suppress the warning (i.e. it still gets triggered, just doesn't show)?
karl
I actually used this in production code on the same day I posted it. The @ suppresses the warning. I prefer my way, since it's one line of code with one or two lines of comments, which imho makes it a lot easier to read for whoever has to maintain it later.
Sparr
+2  A: 

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 ) 
zaf