We help IT Professionals succeed at work.

sorting array list based on   files extension  in php?

prashanth ag
prashanth ag asked
on
Hi
Is it possible in PHP to do something like this?Here is an example.

print_r($content);
Array
(
    [2] => /userupload/one.exe
    [3] => /userupload/avatar.jpg
    [0] => /userupload/two.exe
    [1] => /userupload/three.jpg
    [4] => /userupload/three.exe
)

Open in new window



but i want array sort based on  file extension like .exe , .jpg,.pdf etc
Array
(
    [2] => /userupload/one.exe
    [4] => /userupload/three.exe
    [0] => /userupload/two.exe
    [3] => /userupload/avatar.jpg
    [1] => /userupload/three.jpg
   )

Open in new window

Comment
Watch Question

Most Valuable Expert 2011
Top Expert 2016
Commented:
http://iconoun.com/demo/temp_prasan.php

<?php // demo/temp_prasan.php

/**
 * See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28634602.html
 */
error_reporting(E_ALL);
echo '<pre>';

$arr = array
( '/userupload/one.exe'
, '/userupload/avatar.jpg'
, '/userupload/two.exe'
, '/userupload/three.jpg'
, '/userupload/three.exe'
)
;

// SHOW THE UNSORTED ARRAY
print_r($arr);

// MAKE OBJECTS FROM EACH FILE NAME
$objs = array();
foreach($arr as $position => $filename)
{
    // ISOLATE THE FILE EXTENSION, PRESERVING THE ORIGINAL POSITIONAL ORDER
    $ext = explode('.', $filename);
    $ext = end($ext);
    $obj = new StdClass;
    $obj->ext = $ext . $position;
    $obj->filename = $filename;
    $objs[] = $obj;
}

// A FUNCTION TO COMPARE OBJECT PROPERTIES
function cmp_ext($a, $b)
{
    if     ($a->ext == $b->ext) return 0;
    return ($a->ext <  $b->ext) ? -1 : 1;
}

// SORT THE DATA
usort($objs, 'cmp_ext');

// RECOVER THE SORTED ARRAY
$arr = array();
foreach ($objs as $obj)
{
    $arr[] = $obj->filename;
}

// SHOW THE SORTED ARRAY
print_r($arr);

Open in new window

Freelancer
Top Expert 2010
Commented:
You can do something like this if you want it sorted only by extension:

<?php
function sort_array_by_ext($arr)
{
	$i = 0;
	foreach ($arr as $a)
	{
		$index = 'idx'.$i;
		$parts = explode('.', $a);
		$path[$index] = $parts[0];
		$ext[$index] = $parts[1];
		$i++;
	}
	asort($ext);
	foreach ($ext as $key => $value)
	{
		$resultArray[] = $path[$key] . "." . $value;
	}
	return $resultArray;
}
$arr = array
(
    "/userupload/one.exe",
    "/userupload/avatar.jpg",
    "/userupload/two.exe",
    "/userupload/three.jpg",
    "/userupload/three.exe"
);
echo "<pre>";
var_dump(sort_array_by_ext($arr));
echo "</pre>";

Open in new window

But the result you have shown is sorted not only by extension but even by filename? Do you need this too?
prashanth agsoftware engineer

Author

Commented:
thanks for  Marco Gasi and Ray Paseur