[RESOLVED] Create one array from another
Say I got one array:
array('apple', 'banana','apple','orange','orange','apple');
so i got 3 apples, 1 banana, 2 orange
I want to turn this into another array where the key is the fruit name, and the value is the number of times that fruit is in the first array
sth like: array('apple'=>3,'banana=>1,'orange'=>2)
make sense?
Re: Create one array from another
Try this:
PHP Code:
$fruits = array('apple', 'banana','apple','orange','orange','apple');
$newFruits = array(); //the new array FruitName => Count
foreach($fruits as $fruit)
{
if(array_key_exists($fruit, $newFruits))
{
$newFruits[$fruit]++;
}
else
{
$newFruits[$fruit] = 1;
}
}
// the for loop builds the new array with the counts, print it out to see the results
print_r($newFruits);
Re: Create one array from another
Re: Create one array from another
the182guy: Thanks a lot writing some code man. That was exactly what I was looking for, as I also never would imagine the following already exists.
Quote:
array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.
Thanks a lot for that penagate.
Re: [RESOLVED] Create one array from another
I just learned that if you just want to join two arrays and eliminate the duplicate keys, just do a $array1 + $array2. The resulting array will only have the items with same key's once.
Not very "safe to use" (seeing the items might have same keys, but different values), but that think can be useful sometimes.
Didn't know.