Current Location: Home> Latest Articles> How to Correctly Sort an Array with Negative Numbers in Descending Order Using rsort()

How to Correctly Sort an Array with Negative Numbers in Descending Order Using rsort()

gitbox 2025-08-28
<span><span><span class="hljs-meta">&lt;?php</span></span><span>
</span><span><span class="hljs-comment">// This code snippet is unrelated to the main content and serves only as an example</span></span><span>
</span><span><span class="hljs-keyword">echo</span></span><span> </span><span><span class="hljs-string">"PHP array sorting example starts\n"</span></span><span>;
</span><span><span class="hljs-meta">?&gt;</span></span><span>
<p><hr></p>
<p></span><?php<br>
/**</p>
<ul>
<li>
<p>How to correctly sort an array with negative numbers in descending order using rsort()</p>
</li>
<li></li>
<li>
<p>In PHP, the rsort() function is used to sort an array in descending order. It modifies the original array directly,</p>
</li>
<li>
<p>and by default, it sorts numerically for numbers or alphabetically for strings.</p>
</li>
<li></li>
<li>
<p>For arrays containing negative numbers, rsort() works properly without extra handling,</p>
</li>
<li>
<p>as negative numbers are correctly compared numerically and placed after positive numbers in descending order.</p>
</li>
<li></li>
<li>
<p>Example code:<br>
*/</p>
</li>
</ul>
<p>$numbers = [3, -1, 4, -5, 0, 2, -3];</p>
<p>echo "Array before sorting:\n";<br>
print_r($numbers);</p>
<p>rsort($numbers);  // Sort in descending order using rsort</p>
<p>echo "Array after rsort() (descending order):\n";<br>
print_r($numbers);</p>
<p>/**</p>
<ul>
<li>
<p>Output:</p>
</li>
<li>
<p>Array before sorting:</p>
</li>
<li>
<p>Array</p>
</li>
<li>
<p>(</p>
</li>
<li>
  • [1] =&gt; -1
    
  • [2] =&gt; 4
    
  • [3] =&gt; -5
    
  • [4] =&gt; 0
    
  • [5] =&gt; 2
    
  • [6] =&gt; -3
    
  • )

  • Array after rsort() (descending order):

  • Array

  • (

  • [0] =&gt; 4
    
  • [1] =&gt; 3
    
  • [2] =&gt; 2
    
  • [3] =&gt; 0
    
  • [4] =&gt; -1
    
  • [5] =&gt; -3
    
  • [6] =&gt; -5
    
  • )

  • As you can see, negative numbers are correctly placed after positive numbers, and the array is properly sorted in descending order.

  • Notes:

    • rsort() sorts numeric arrays in descending numeric order and string arrays in descending dictionary order by default.

    • If an array contains mixed types (numbers and strings), sorting behavior may be unexpected.

  • It's recommended to unify types first or use a custom sort function (usort) for handling.
    */

  • ?>

    <?php
    // This code snippet is unrelated to the main content and serves only as an example ending
    echo "PHP array sorting example ends\n";
    ?>