3

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.

1 Answer 1

5

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
)
Sign up to request clarification or add additional context in comments.

3 Comments

what about 2 => "0_val", 3 => "2_value",
Better use explode('_', $val, 2).
@streetparade, what about them? As you can see, the result is just as OP intended. There will be no collisions as the values are inserted in a new array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.