Sort array by string length in PHP

/**
 * Sorts array by string length.
 *
 * From shortest to longest: `return ( strlen( $a ) - strlen( $b ) );`
 * From longest to shortest: `return ( strlen( $b ) - strlen( $a ) );`
 *
 * @see https://wpcodebook.com/sort-array-string-length-php/
 * @see https://www.php.net/manual/en/array.sorting.php
 * @see https://www.php.net/manual/en/function.usort.php
 * @see https://www.php.net/manual/en/function.strlen.php
 */
function wpcodebook_sort_by_string_length( &$data ) {
	usort( $data, function ( $a, $b ) {
		return ( strlen( $b ) - strlen( $a ) );
	} );
}

Example

$example_array = array(
	'Lorem',
	'ipsum',
	'dolor',
	'sit',
	'amet',
	'consectetur',
	'adipiscing',
	'elit',
	'sed',
	'do',
	'eiusmod',
	'tempor',
	'incididunt',
	'ut',
	'labore',
	'et',
	'dolore',
	'magna',
	'aliqua',
);

wpcodebook_sort_by_string_length( $example_array );

echo '<pre>' . print_r( $example_array, true ) . '</pre>';

Output:

Array
(
    [0] => consectetur
    [1] => adipiscing
    [2] => incididunt
    [3] => eiusmod
    [4] => tempor
    [5] => labore
    [6] => dolore
    [7] => aliqua
    [8] => Lorem
    [9] => ipsum
    [10] => dolor
    [11] => magna
    [12] => amet
    [13] => elit
    [14] => sit
    [15] => sed
    [16] => do
    [17] => ut
    [18] => et
)

Leave a Comment