# Sort array of arrays based on value inside the inner array

**URL:** <https://www.phphelp.com/t/sort-array-of-arrays-based-on-value-inside-the-inner-array/35205>\
**Category:** General PHP Help\
**Created:** [January 3, 2023, 11:54pm UTC](https://www.phphelp.com/t/sort-array-of-arrays-based-on-value-inside-the-inner-array/35205 "2023-01-03T23:54:52Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![conexor](https://www.phphelp.com/user_avatar/www.phphelp.com/conexor/32/4155_2.png) [@conexor](https://www.phphelp.com/u/conexor)\
**Post date:** [January 3, 2023, 11:54pm UTC](https://www.phphelp.com/t/sort-array-of-arrays-based-on-value-inside-the-inner-array/35205/1 "2023-01-03T23:54:52Z")

</div>

I have an array of arrays like the first array.  
I would like to sort it in the order based on key3 in the second inner array  
note I need to keep the keys from both arrays  
How can I do this?

[1] =\> Array  
(  
[key1] =\> 123  
[key2] =\> ‘apple’  
[key3] =\> 10  
[key4] =\> ‘comment1’  
)

[2] =\> Array  
(  
[key1] =\> 234  
[key2] =\> ‘PEAR’  
[key3] =\> 4  
[key4] =\> ‘comment2’  
)

[3] =\> Array  
(  
[key1] =\> 456  
[key2] =\> ‘ORANGE’  
[key3] =\> 5  
[key4] =\> ‘comment3’  
)

[4] =\> Array  
(  
[key1] =\> 679  
[key2] =\> ‘grape’  
[key3] =\> 1  
[key4] =\> ‘comment4’  
)

The result would look like this:  
[4] =\> Array  
(  
[key1] =\> 679  
[key2] =\> ‘grape’  
[key3] =\> 1  
[key4] =\> ‘comment4’  
)   
[2] =\> Array  
(  
[key1] =\> 234  
[key2] =\> ‘PEAR’  
[key3] =\> 4  
[key4] =\> ‘comment2’  
)  
[3] =\> Array  
(  
[key1] =\> 456  
[key2] =\> ‘ORANGE’  
[key3] =\> 5  
[key4] =\> ‘comment3’  
)  
[1] =\> Array  
(  
[key1] =\> 123  
[key2] =\> ‘apple’  
[key3] =\> 10  
[key4] =\> ‘comment1’  
)

---

<div class="post-metadata">

**Author:** ![phdr](https://www.phphelp.com/letter_avatar_proxy/v4/letter/p/91b2a8/32.png) [@phdr](https://www.phphelp.com/u/phdr)\
**Post date:** [January 4, 2023, 1:17am UTC](https://www.phphelp.com/t/sort-array-of-arrays-based-on-value-inside-the-inner-array/35205/2 "2023-01-04T01:17:42Z")

</div>

See - [PHP: uasort - Manual](https://www.php.net/manual/en/function.uasort.php)

Call-back function to sort using the key3 entries -

```auto
function sorter(array $a, array $b) {
    return $a['key3'] <=> $b['key3'];
}
```

Assuming your data is in $data -

```auto
uasort($data, 'sorter');
```

---

<div class="post-metadata">

**Author:** ![conexor](https://www.phphelp.com/user_avatar/www.phphelp.com/conexor/32/4155_2.png) [@conexor](https://www.phphelp.com/u/conexor)\
**Post date:** [January 11, 2023, 8:58pm UTC](https://www.phphelp.com/t/sort-array-of-arrays-based-on-value-inside-the-inner-array/35205/3 "2023-01-11T20:58:23Z")

</div>

Thank you. Worked a treat 🙂
