Sorting multidimensional PHP arrays by object values with accentuated character

William L'Archevêque
2 min readOct 4, 2020

--

When working on a multilingual website, it often happens that we need to deal with special and accentuated characters.

When working on a multilingual website, it often happens that we need to deal with special and accentuated characters. In Québec (Canada), Websites are most of the time, bilingual. This can cause a headache to developers when dealing with sorting arrays by alphabetical order due to “caractères spéciaux” (french for special characters).

I developed a few methods that can help overcome the difficulties of multidimensional array sorting.

The problem

Let’s say we have a multidimensional array of categories objects returned by an API that we want to order alphabetically by category name for a specific language :

It’s a challenge to order this array correctly because of the accentuated characters and because of the way the array is formatted (with an array of objects).

The solution

I have solved this problem by creating two different functions in a StringHelper.php class that can be used in the application :

StringHelper.php

The two functions look complicated at first sight, but they are not really.

Explanation and result (sorting the multidimensional array) 🧙‍♂️

The first function receives 3 parameters, the multidimensional array reference (or array of objects), the element and key that are used to sort the array.

Let’s say we want to order the previous array by french names. The parameters would be :

alphabeticalCompareArrayByKey($categories, 'names', 'fr');

As we are sending the array as a reference, no need to reassign it into a variable. The usort function sorts an array by values using a user-defined comparison function. Our comparison function is a binary safe case-insensitive string comparison : strcasecmp().

Within the comparison we make sure the accentuated characters are replaced with the adequate ones (ie. é = e, â = a).

Our comparison will then be successful. 💪

The previous example only works with an array of objects, but you could easily adapt it to compare an array of array by modifying the strcasecmp() part by :

return strcasecmp(self::transliterateString($a[$element][$key]), self::transliterateString($b[$element][$key]));

Let me know if this article helped you to sort your sorting problems and leave claps if it helped !

--

--

William L'Archevêque

Full-Stack Web Developer. Enthusiast Helper. Freelancer for 7 years, now having fun working at Centiva. Specialized in Laravel PHP, AWS Cloud and cartwheeling.