3v4l.org

run code in 300+ PHP versions simultaneously
<?php // groupA: // James: // gpa: 3 // age: 13 // Charles: // gpa: 4 // age: 15 // John: // gpa: 2 // age: 17 $groupA = [ 'James' => [ 'gpa' => 3, 'age' => 13 ], 'Charles' => [ 'gpa' => 4, 'age' => 15 ], 'John' => [ 'gpa' => 2, 'age' => 17 ] ]; /** * @throws \InvalidArgumentException */ function getPlace(string $for, string $compareValueKey, array $haystack, int $flags = SORT_REGULAR): int { if(empty($haystack) || !isset($haystack[$for])) { throw new \InvalidArgumentException("empty haystack array given (or key '$for') was not found"); } $sort = array_map(fn(array $el) => $el[$compareValueKey], $haystack); arsort($sort, $flags); $place = array_search($for, $places = array_keys($sort), true); if(!is_int($place)) { throw new \RuntimeException("could not locate position for key '$for' in given array: " . trim(implode(', ', $places))); } return $place + 1; } $persons = array_keys($groupA); foreach($persons as $person) { echo $person . ': ' . getPlace($person, 'age', $groupA) . PHP_EOL; }
Output for 8.0.9, 8.1.23 - 8.1.28, 8.2.10 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
James: 3 Charles: 2 John: 1
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 James: 3 Charles: 2 John: 1

preferences:
72.27 ms | 402 KiB | 28 Q