× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Easy custom number sort

<p>Sometimes you cannot rely on build in sort functions of PHP. For example if you have to sort an array of records retrieved from a database. As an example here is a list of people with their name and age:</p> <pre><code class="language-php">$array = [ [ "name" =&gt; "Jakob", "age" =&gt; "37" ], [ "name" =&gt; "Topher", "age" =&gt; "18" ], [ "name" =&gt; "Ginger", "age" =&gt; "43" ], ]; </code></pre> <p>To sort these records by age we will use <strong><em>usort</em></strong>. The general idea is that you supply a function that return -1 for smaller than, 0 for equal to and 1 for bigger than.</p> <pre><code class="language-php">usort($array, function ($a, $b) { if ($a["age"] == $b["age"]) { return 0; } return (int) $a["age"] &lt; (int) $b["age"] ? -1 : 1; });</code></pre> <h2>TIP #1</h2> <p>Since our age is just a number we don't actually have to do the three checks for lesser than, equal to and larger than. We can simply deduct the numbers from each other and we will get a number satisfying the compare function.</p> <pre><code class="language-php">usort($array, function ($a, $b) { return (int) $a["age"] - (int) $b["age"]; });</code></pre> <p>So if $a's age is less than $b's age we get a negative number. If they are of the same age we get 0 and if $a is older then we get a positive number.</p> <p>This works for for decimal numbers as well.</p> <h2>Tip #2</h2> <p>But we can make it even simpler. We can make use of the fact that PHP auto-juggles types depending on the operations performed on them. Since - (minus) is something that you do on numbers and not strings we actually do not have to cast out values from the database to strings:</p> <pre><code class="language-php">usort($array, function ($a, $b) { return $a["age"] - $b["age"]; }</code></pre> <p>Our sort function has become much simpler, thus easier to comprehend.</p> <h2>Tip #3</h2> <p>Another way to sort arrays of records like this is to use PHP's <em><strong>array_multisort</strong></em> function. The function can be a bit intimidating to read about in the docs, but basically it takes two arrays. It sorts the first one and then rearranges the second one by the same indices. </p> <pre><code class="language-php">array_multisort(array_column($array, "age"), $array); </code></pre> <p>In the example above we extract all the age values from our records. These will function as our sort array or guiding array as to how the actually array of records should be sorted.</p> <p>Keeping your code simple and understandable is a big part of writing beautiful and good code. With a little knowledge about how PHP works you can come a long way.</p> <p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus