How can substr() function in PHP be utilized to extract a specific number of characters from a string for sorting purposes?

When sorting strings in PHP, you may need to extract a specific number of characters from each string to use as a sorting key. The substr() function in PHP can be utilized for this purpose. By extracting a substring of a fixed length from each string, you can create a custom sorting algorithm based on these substrings.

// Example code to extract the first 5 characters from a string for sorting purposes
$strings = ["apple", "banana", "cherry", "date"];

usort($strings, function($a, $b) {
    $substring_length = 5;
    $sub_a = substr($a, 0, $substring_length);
    $sub_b = substr($b, 0, $substring_length);
    
    return strcmp($sub_a, $sub_b);
});

print_r($strings);