Phani Shashank Phani Shashank - 1 month ago 8
PHP Question

Split array based on value for a single dimentional array with key and value

I am trying to split an array to different arrays based on values.
This is my array

$myArray=('x'=>'europe','y'=>'europe','a'=>'USA','b'=>'USA','c'=>'Canada');


I want to split the array based on value like below

$newList[europe]=(x,y);
$newList[USA]=(a,b);
$newLsit[Canada]=(c);


I tried the following

foreach($myArray as $key =>$value){
$myList[$value]=$key;
}


and

foreach($myArray as $key => $value){
echo $key;
if($value=='USA')$myList['USA']=$key;
if($value=='europe')$myList['europe']=$key;
if($value=='Canada')$myList['Canada']=$key;
}


the output is the same

Array ( [europe] => y [USA] => b [Canada] => c )


I do not understand what the issue could be. Any help is much appriciated.

Answer

If you have more countries, then if loop is not a good method. Instead of that you can create array for each country using foreach statement. Please see the below code, it may help you.

    $myArray = array('x'=>'europe','y'=>'europe','a'=>'USA','b'=>'USA','c'=>'Canada');
    $new_array = array();
    foreach($myArray as $key=>$val)
    {
      $new_array[$val][] = $key;
    }
    print_r($new_array);
Comments