3

Here's my array:

    [a] => apple
    [b] => banana
    [c] => Array
    (
        [2] => x
        [4] => y
        [6] => z
    )

I'm looking for a way to put my [c] array variables in "order". Making my array, look like this:

    [a] => apple
    [b] => banana
    [c] => Array
(
        [1] => x
        [2] => y
        [3] => z
)

Is there a way to do it without creating a new function by myself?

2
  • Fortunately PHP provides a lot of sorting functions, you don't have to write another one. Try sort($a['c']) (assuming your array is stored in the $a variable). Commented Jul 21, 2017 at 9:44
  • The values in $a['c'] are already in order. Is it important to have their keys starting with 1? Commented Jul 21, 2017 at 9:59

3 Answers 3

4

Just try with reassigning c value:

$data['c'] = array_values($data['c']);

It will reindex your c array, but the indexes will start with 0. If you really want to start with 0, try:

$data['c'] = array_combine(range(1, count($data['c'])), array_values($data['c']))
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome!! That's it, thanks a lot! :) I'll mark this as an answer asap
And also, I didn't mean to have them start from 1, my mistake. Thanks once again
2

Fortunately PHP provides a lot of functions for array sorting, you don't have to write another one.

Try sort($a['c']) (assuming your array is stored in the $a variable).

$a = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => array(
        '1' => 'x',
        '2' => 'y',
        '3' => 'z',
    ),
);

sort($a['c']);
print_r($a);

The output:

Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)

If you don't need to sort the content of $a['c'] and only want to re-index it (let it have numeric consecutive keys starting with 0) then array_values() is all it needs:

$a['c'] = array_values($a['c']);

Comments

1

If you don't know how many arrays needs to be sorted, try this:

$testarr = ['a' => 'apple', 'b' => 'banana', 'c' => ['x', 'y', 'z']];

foreach ($testarr as $key => $item) {
    if (is_array($item)) { $arr[$key] = array_values($item); }
    // if (is_array($item)) { $arr[$key] = asort($item); } // use asort() if you want to keep subarray keys
}

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.