Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I have the folloring array structure:

$list = array();
$element1 = array('start' => '10', 'end' => '15');
$element2 = array('start' => '1',  'end' => '5');
$list[] = $element1;
$list[] = $element2;

Every element in start and end are numeric only.

I would like to sort $list by start values. How can I do that effectivly?

share|improve this question

marked as duplicate by deceze Jun 20 '14 at 13:21

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Is start value meant to be a string or a numeric? It will make a small difference to the answer –  Mark Baker Aug 10 '10 at 14:16

2 Answers 2

up vote 4 down vote accepted

You can use usort with this comparison function:

function cmp($a, $b) {
    if ($a['start'] == $b['start']) {
        return $a['end'] - $b['end'];
    } else {
        return $a['start'] - $b['start'];
    }
}

With this comparison function the elements are ordered by their start value first and then by their end value.

share|improve this answer
function cmp($a, $b)
{
    if ($a['start'] == $b['start']) {
        return 0;
    }
    return ($a['start'] < $b['start']) ? -1 : 1;
}

$list = array();
$element1 = array('start' => '10', 'end' => '15');
$element2 = array('start' => '1',  'end' => '5');
$list[] = $element1;
$list[] = $element2;

usort($list, "cmp");
share|improve this answer
    
+1. Just to elaborate for the person asking the question, this uses PHP's user defined sort referenced here: php.net/manual/en/function.usort.php –  Fosco Aug 10 '10 at 14:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.