What are some common pitfalls when trying to sort arrays with the same key in PHP?

When trying to sort arrays with the same key in PHP, a common pitfall is not specifying a secondary sorting criteria when the primary key values are equal. To solve this issue, you can use the spaceship operator (<=>) in the custom sorting function to compare secondary keys if the primary keys are equal.

// Example array with same key values
$items = [
    [&#039;key&#039; =&gt; 2, &#039;secondary_key&#039; =&gt; 5],
    [&#039;key&#039; =&gt; 1, &#039;secondary_key&#039; =&gt; 3],
    [&#039;key&#039; =&gt; 2, &#039;secondary_key&#039; =&gt; 1],
];

// Custom sorting function to handle same key values
usort($items, function($a, $b) {
    if ($a[&#039;key&#039;] == $b[&#039;key&#039;]) {
        return $a[&#039;secondary_key&#039;] &lt;=&gt; $b[&#039;secondary_key&#039;];
    }
    return $a[&#039;key&#039;] &lt;=&gt; $b[&#039;key&#039;];
});

// Output sorted array
print_r($items);