Thomas Valadez Thomas Valadez - 4 months ago 27
PHP Question

usort within a custom function in php

I am trying to make a really cool super sort function, however the user sort functionality doesn't work when created as a funtion inside. The idea is to name the array and key then it returns the sorted array according to my choice.

function super_sort($key,$arr){
usort($arr, function($a, $b){
return strcmp($a[$key], $b[$key]);

I would call it like this


also I should add the print_sorted function is this

function print_sorted($key,$arr){
echo '<h1>'.$key.'</h1>';
foreach($arr as $k => $v){
echo '<strong>name:</strong> '.$v['name'].'<strong> age:</strong> '.$v['age'].'<strong> social:</strong> '.$v['social'].'<strong> index:</strong> '.$v['index'].'<br/>';


$key doesn't exist in the context of your anonymous function so pass it using use.

usort($arr, function($a, $b) use ($key) {
    return strcmp($a[$key], $b[$key]);