Skip to content
PHP Logo

What are some potential pitfalls when sorting multidimensional arrays in PHP, especially when it comes to sorting by street names and house numbers?

When sorting multidimensional arrays in PHP, especially when sorting by street names and house numbers, a potential pitfall is that the sorting may not be accurate if the data is not formatted consistently. To solve this, you can use a custom sorting function that properly handles the sorting based on both street names and house numbers.

php
// Sample multidimensional array with street names and house numbers
$data = array(
    array('street' => 'Main St', 'house_number' => 100),
    array('street' => 'Elm St', 'house_number' => 50),
    array('street' => 'Main St', 'house_number' => 75),
);

// Custom sorting function to sort by street name and then house number
usort($data, function($a, $b) {
    if ($a['street'] == $b['street']) {
        return $a['house_number'] - $b['house_number'];
    }
    return strcmp($a['street'], $b['street']);
});

// Output sorted array
print_r($data);