Search code examples
phparraysassociative-array

Remove prefix from all strings in a flat array and use them as keys, then sort by keys


I have this array:

Array
    (
      0 => "3_some val",
      1 => "1_some other val",
      2 => "0_val",        
      3 => "2_value",
      4 => "4_other value"
    )

considering the above array, is there a way to do from that an array like this?

Array
    (
      0 => "val",
      1 => "some other val",
      2 => "value",        
      3 => "some val",
      4 => "other value"
    )

actually to force the number that precedes that underscore(_) to be the key in the newly created array.


Solution

  • This should do it:

    $arr1 = array (
      0 => "3_some val",
      1 => "1_some other val",
      2 => "0_val",        
      3 => "2_value",
      4 => "4_other value"
    );
    
    $result = array();
    
    foreach($arr1 as $val) {
        list($key, $value) = explode('_', $val, 2);
        $result[$key] = $value;
    }
    
    // Sort by keys
    ksort($result);
    

    Doing print_r($result) will print out:

    Array
    (
        [0] => val
        [1] => some other val
        [2] => value
        [3] => some val
        [4] => other value
    )