3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * Works fine if the key are not numerical */ $arrTags = []; $arrTags['mango'] = 2; $arrTags['orange'] = 4; $arrTags['apple'] = 2; $arrTags['banana'] = 3; array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags); echo "Elegant solution works fine if keys are not numerical:\r\n"; var_dump($arrTags); /** * If keys are numerical, they will be ignored */ $arrTags = []; $arrTags[10] = 2; $arrTags[20] = 4; $arrTags[30] = 2; $arrTags[40] = 3; array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags); echo "If keys are numerical, they will be ignored:\r\n"; var_dump($arrTags); /** * A slightly less elegant solution will work. */ $arrTags = []; $arrTags[10] = 2; $arrTags[20] = 4; $arrTags[30] = 2; $arrTags[40] = 3; $keys= array_keys($arrTags); $values= array_values($arrTags); array_multisort($values, SORT_DESC, $keys, SORT_ASC); $arrTags = array_combine($keys, $values); echo "If numerical keys are important, the slightly less elegant solution will work:\r\n"; var_dump($arrTags);
Output for 5.6.38, 7.0.33, 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
Elegant solution works fine if keys are not numerical: array(4) { ["orange"]=> int(4) ["banana"]=> int(3) ["apple"]=> int(2) ["mango"]=> int(2) } If keys are numerical, they will be ignored: array(4) { [0]=> int(4) [1]=> int(3) [2]=> int(2) [3]=> int(2) } If numerical keys are important, the slightly less elegant solution will work: array(4) { [20]=> int(4) [40]=> int(3) [10]=> int(2) [30]=> int(2) }
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Elegant solution works fine if keys are not numerical: array(4) { ["orange"]=> int(4) ["banana"]=> int(3) ["apple"]=> int(2) ["mango"]=> int(2) } If keys are numerical, they will be ignored: array(4) { [0]=> int(4) [1]=> int(3) [2]=> int(2) [3]=> int(2) } If numerical keys are important, the slightly less elegant solution will work: array(4) { [20]=> int(4) [40]=> int(3) [10]=> int(2) [30]=> int(2) }

preferences:
141.11 ms | 403 KiB | 154 Q