Note that there are some explanatory texts on larger screens.

plurals
  1. POSort strings that also contain some integers
    text
    copied!<p>Using <code>usort()</code>, is it possible to sort strings that also contain integer values?</p> <p>For example, take this array of objects containing email addresses (and other data) -</p> <pre><code>$invitees = Array( [0] =&gt; Array( 'email' =&gt; 'test11@testing.com' ), [1] =&gt; Array( 'email' =&gt; 'test2@testing.com' ), [2] =&gt; Array( 'email' =&gt; 'test1@testing.com' ) ); </code></pre> <p>Using the following code compares the array elements as just a simple string -</p> <pre><code>/** Sort the data (if the sort key is defined) */ if(!empty($_REQUEST['orderby'])) : usort($emails, array(&amp;$this, '_order_callback')); endif; function _order_callback($item_a, $item_b){ /** Grab 'orderby', which must have been set for this function to be called */ $orderby = $_REQUEST['orderby']; /** If no 'order' is not set, default to ASC */ $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'ASC'; $result = strcmp($item_a[$orderby], $item_b[$orderby]); return (strtoupper($order) === 'ASC') ? $result : -$result; //Send final sort direction to usort } </code></pre> <p>The results are delivered in the following order -</p> <pre><code>[0] - 'test11@testing.com' [2] - 'test1@testing.com' [1] - 'test2@testing.com' </code></pre> <p>Where as I desire this order -</p> <pre><code>[2] - 'test1@testing.com' [1] - 'test2@testing.com' [0] - 'test11@testing.com' </code></pre> <p>Is this possible with <code>usort()</code>? Thanks.</p> <hr> <h2>Edit</h2> <p>Now that I know of the existence of <code>natsort()</code> (thanks to the below comments/answers), I was able to find and try this -</p> <pre><code>$result = ($item_a[$orderby] &gt; $item_b[$orderby] ? 1 : ($item_a[$orderby] &lt; $item_b[$orderby] ? -1 : 0)); </code></pre> <p>I added that comparison to my <code>_order_callback()</code> function (if <code>$orderby === email</code>), and it's close, but sorts in the order <code>11, 12, 13, 14, 1, 2, 3, 4</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload