Skip to content

Instantly share code, notes, and snippets.

@khoipro
Last active May 30, 2024 03:12
Show Gist options
  • Save khoipro/96ac503ac2cf03df898bd7daeee78018 to your computer and use it in GitHub Desktop.
Save khoipro/96ac503ac2cf03df898bd7daeee78018 to your computer and use it in GitHub Desktop.
Sort items in PHP array, define only first and specific index item
<?php
$first_id = 110;
$items = [
[
'id' => 101,
'content' => 'Test 1'
],
[
'id' => 110,
'content' => 'Test 2'
],
[
'id' => 120,
'content' => 'Test 3'
],
[
'id' => 125,
'content' => 'Test 3'
]
];
$_items = [];
foreach( $items as $index => $item ) {
$item['order'] = 0;
if ($item['id'] === $first_id) {
$item['order'] = 0; // Sort to first
}
if ($index === 2) {
$item['order'] = 2; // Sort to last
}
$_items[] = $item;
}
// PHP 7.4
usort($items, fn($a, $b) => $a['order'] <=> $b['order']);
// Result: 110, 101, 125, 120
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment