In PHP, how do I sort arrays with strong typing?

PHP, strong typing, sort arrays, type-safe sorting, PHP array sort
This guide explains how to sort arrays in PHP while maintaining strong typing, ensuring that elements are sorted according to their type and value.

<?php
// Function to sort arrays with strong typing
function sortArray(array $array) : array {
    // Filter values to ensure only integers and strings are considered
    $filtered = array_filter($array, function($value) {
        return is_int($value) || is_string($value);
    });
    
    // Sort the filtered array
    sort($filtered);
    
    return $filtered;
}

$inputArray = [3, "apple", 2, "banana", 1, "orange"];
$sortedArray = sortArray($inputArray);

print_r($sortedArray);
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => apple [4] => banana [5] => orange )
?>
    

PHP strong typing sort arrays type-safe sorting PHP array sort