Phani Shashank Phani Shashank - 1 year ago 71
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


I want to split the array based on value like below


I tried the following

foreach($myArray as $key =>$value){


foreach($myArray as $key => $value){
echo $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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download