<span><span><span class="hljs-meta"><?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">?></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] => -1
[2] => 4
[3] => -5
[4] => 0
[5] => 2
[6] => -3
)
Array after rsort() (descending order):
Array
(
[0] => 4
[1] => 3
[2] => 2
[3] => 0
[4] => -1
[5] => -3
[6] => -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";
?>