views:

72

answers:

3

I have an array like this:

array(
    0 => array("src" => "foo-21.gif"),
    1 => array("src" => "bar-short.gif"), 
    2 => array("src" => "baz-1.gif"), 
    3 => array("src" => "whatever.gif"), 
    4 => array("src" => "some-long.gif"), 
    5 => array("src" => "xyz.gif"), 
);

The value in the src element can be anything.

However there will only be max. one element containing short (here it is element 1) and only max. one elment containing long (here it is element 4). They can be anywhere in the array. Or not present at all.

What I need to do now is:

  • The element with src containing short must be first if present
  • The element conaining long must be last if present
  • The order in between does not matter.

So the example would look like this:

array(
    0 => array("src" => "bar-short.gif"), // containing "short" = first
    1 => array("src" => "foo-21.gif"), 
    2 => array("src" => "baz-1.gif"), 
    3 => array("src" => "whatever.gif"), 
    4 => array("src" => "xyz.gif"), 
    5 => array("src" => "some-long.gif"), // containing "long" = last
);

How would I do this? usort does not seem like a good idea here.

+2  A: 

usort() could actually work just fine here; return -1 if the first argument has "short" and/or the second argument has "long", 1 if vice versa, and 0 (or anything, really) if neither is the case.

Amber
+1  A: 

Assuming your array is $list:

function short_long_sort($a, $b)
{
    $short_str = '-short';
    $long_str = '-long';
    if (strpos($a['src'], $short_str)) return -1;
    if (strpos($b['src'], $short_str)) return 1;
    if (strpos($a['src'], $long_str)) return 1;
    if (strpos($b['src'], $long_str)) return -1;
    return 0;
}

usort($list, 'short_long_sort');
print_r($list);
scribble
Edit to replace preg_match() with strpos(). Everybody knows SO loves `(?!regex)`.
scribble
Nice! Did exactly what I needed!
Max
A: 

Alternatively, you don't need to sort anything if you just track which elements have "short" and "long" when you input them, then eg:

process($arr->[$short]);
for ($i=0; $i < @$arr; $i++) {
  process($arr->[$i]) if (($i != $short) && ($i != $long));
}
process($arr->[$long]);
Hairy Jock