3

If I have an associative array that is structured like

(
    1 => 'a',
    2 => 'b',
    0 => 'c'
)

where all of the keys are numeric, will array_values ALWAYS guarantee that the values occur chronologically, in the new array, based on their previous keys' values, i.e. ['c', 'a', 'b']?

If not, how can I accomplish this instead?

2
  • numeric keys points to indexed array, not associative Commented Feb 27, 2017 at 21:58
  • @RomanPerekhrest Not always. In this case the keys are sequential, but what if they weren't, such as 1, 3, and 5? Commented Feb 27, 2017 at 21:59

2 Answers 2

7

No, array_values() will not reorder the values in any way. It doesn't care about keys.

Its effective implementation is basically this:

function array_values_impl(array $array)
{
    $newArray = [];

    foreach ($array as $item) {
        $newArray[] = $item;
    }

    return $newArray;
}

If you want to sort the array using the keys, use ksort().

Sign up to request clarification or add additional context in comments.

Comments

3

You can accomplish by first sorting the array with keys and getting values by array_values function.

For example

 $array = array(
    1 => 'a',
   2 => 'b',
   0 => 'c'
);

ksort($array);
print_r(array_values($array));

Output:

Array
(
    [0] => c
    [1] => a
    [2] => b
)

Comments

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.