I wanted to use usort()
function to sort array by it's values' lengths. Here is my function:
$max_min_length = function ($a, $b) {
if (strlen($a) > strlen(b))
return 1;
elseif (strlen($a) < strlen(b))
return -1;
else
return 0;
};
$array = ["abcd","abc","de","hjjj","g","wer"];
usort($array, $max_min_length);
print_r($array);
The output is:
Array ( [0] => g [1] => abcd [2] => abc [3] => hjjj [4] => de [5] => wer )
I cannot understand, why it doesn't sort properly. Am I missing something? I've looked at PHP: Sort an array by the length of its values? and their solutions work just fine. I just want to know, why does this happen? Thanks in advance.
You have typo for "b" without "$"
replace code with:
if (strlen($a) > strlen($b))
return 1;
elseif (strlen($a) < strlen($b))
return -1;
else
return 0;
};
After it your code will work fine :)