1

Following is the array that I want to sort:

// Sample array
$myArray = array(
    "apple" => 2,
    "orange" => 5,
    "banana" => 3,
    "kiwi" => 1,
);

The key that I want to keep on top is:

$specialKey = "banana";
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Rishi Kulshreshtha
  • 1,748
  • 1
  • 24
  • 35
  • 2
    Do you want to sort it by keys or by values ? – Casimir et Hippolyte Mar 23 '23 at 12:47
  • Related page processing 2d array: [PHP make some of the Key to be sticky in an Associative array](https://stackoverflow.com/q/56230671/2943403). Another related page: [Sorting PHP array by value then key by custom order](https://stackoverflow.com/q/68483657/2943403) – mickmackusa Mar 24 '23 at 05:25
  • See my answer from the 5 years ago which demonstrates how to key sort and array with a sticky key: [`uksort($myArray, fn($a, $b) => [$a !== $specialKey, $a] <=> [$b !== $specialKey, $b]);`](https://3v4l.org/enteO) – mickmackusa Mar 24 '23 at 05:39

1 Answers1

2

I can see that you want to sort keys, so here is a shorter way to do the same (as well as performance wise faster):

<?php

// Sample array
$myArray = array(
    "apple" => 2,
    "orange" => 5,
    "banana" => 3,
    "kiwi" => 1,
);

$specialKey = "banana";
$toparray[$specialKey] = $myArray[$specialKey]; //get key-values in new array
unset($myArray[$specialKey]);//unset key-value from original array
ksort($myArray); //sort original array based on key
print_r($toparray+$myArray);//combine both array to get desired result

https://3v4l.org/atKpR

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98