Reputation:
I have an array called $countrySelected. I would like to retrieve the total unique count of countries.
E.g, if theres Afghanistan, Aland Islands, and Afghanistan in the array, the unique count would be 2.
Any pointers, or references in the right direction would be appreciated. Do I somehow merge the arrays, and then count the unique values?
Array
(
[0] => Array
(
[0] => Afghanistan
[1] => Aland Islands
)
[1] => Array
(
[0] => Aland Islands
[1] => Albania
[2] => Algeria
)
[2] => Array
(
[0] => Albania
[1] => Algeria
)
[3] =>
[4] => Array
(
[0] => Albania
[1] => Algeria
)
[5] => Array
(
[0] => Aland Islands
[1] => Albania
[2] => Algeria
)
[6] =>
[7] =>
[8] =>
[9] =>
[10] =>
[11] => Array
(
[0] => Afghanistan
)
[12] =>
[13] =>
[14] =>
[15] =>
[16] =>
[17] =>
[18] =>
[19] => Array
(
[0] => Albania
[1] => Algeria
)
[20] =>
[21] =>
[22] =>
[23] =>
[24] =>
[25] =>
[26] =>
[27] =>
[28] =>
[29] =>
[30] =>
[31] =>
[32] =>
[33] =>
[34] =>
[35] =>
[36] =>
[37] =>
[38] =>
[39] =>
[40] =>
[41] =>
[42] =>
[43] =>
[44] =>
[45] =>
[46] =>
[47] =>
[48] =>
[49] =>
[50] =>
[51] =>
[52] =>
[53] =>
[54] =>
[55] =>
[56] =>
[57] =>
[58] =>
[59] =>
[60] =>
[61] =>
[62] =>
[63] =>
[64] =>
[65] =>
[66] =>
[67] =>
[68] =>
[69] =>
[70] =>
[71] =>
[72] =>
[73] =>
[74] =>
[75] =>
[76] =>
[77] =>
[78] =>
[79] =>
)
Upvotes: 0
Views: 147
Reputation: 32740
Here is the simple solution : No loops :)
$array = array(array("Afghanistan", "Aland Islands"), array("Aland Islands", "Albania", "Albania"));
$result = array_count_values(call_user_func_array('array_merge', $array));
echo "<pre>";
print_r($result);
count($result); // will give you the count of unique countries.
Output :
Array
(
[Afghanistan] => 1
[Aland Islands] => 2
[Albania] => 2
)
Upvotes: 0
Reputation: 4144
I have tried with array_reduce
, using flip of array keys
$uniques = array_reduce( $countries, function ( $carry, $item){
return $item ? $carry + array_flip($item) : $carry;
}, array() );
echo count( array_keys( $uniques) );
Upvotes: 0
Reputation: 1014
You can use built in array function and count to get it for simple array
$ary=array("Af","Bc","Af");
$count=count(array_unique($ary));
echo $count;
for arrays of array use
$countrySelected=array();
foreach ($resarray as $tkey=>$tvalue)
{
if(is_array($tvalue))
{
foreach($tvalue as $finkey=>$finvalue)
{
$countryselected[]=$finvalue;
}
}
}
$count=count(array_unique($countryselected));
echo $count;
Upvotes: 0
Reputation: 2330
<?php
$countries = array();
foreach($given_array as $array){
foreach($array as $country){
if(!in_array($country, $countries)){
$countries[] = $country;
}
}
}
echo count($countries); // prints Total Number of countries
?>
Upvotes: 0
Reputation: 9635
you can do this
$arr_country = array();
foreach($your_array as $arr)
{
foreach($arr as $country)
{
if(!in_array($country, $arr_country))
{
$arr_country[] = $country;
}
}
}
echo "Total Countries : ".count($arr_country);
Upvotes: 1