tags:

views:

91

answers:

3

I want to "include" the last 2 files in my php file based on their names.

So the names are:

01-blahbla.php
02-sdfsdff.php
03-aaaaaaa.php
04-bbbbbbb.php
05-wwwwwwi.php

and I only want to include 05 and 04 since their name starts with the biggest number.

How do I go on about doing this?

A: 

List the directory contents into an array. Sort that array using built-in PHP sorting functions. Do a require_once() on the first two elements of the array.

Alex
+3  A: 

Assuming there is only the numbered files in the folder, you could use

$files = glob('/path/to/files/*.php'); // get all php files in path
natsort($files);                       // sort in natural ascending order
$highest = array_pop($files);          // get last file, e.g. highest number
$second  = array_pop($files);          // again for second highest number
Gordon
@Gordon thank you...
Harish Kurup
+1  A: 

Put the values in an array, reverse sort it using rsort() and then take the first two:

$values = array('01-blahbla.php', '02-sdfsdff.php', '03-aaaaaaa.php', '04-bbbbbbb.php', '05-wwwwwwi.php');
rsort($values);
$file1 = $values[0];
$file2 = $values[1];
require_once $file1;
require_once $file2;

The PHP manual at php.net has some great info for the various sort methods.

Update:

As Psytronic noted, rsort will not work for numbers, but you can create a custom function that easily does the same thing:

function rnatsort(&$values) {
  natsort($values);
  return array_reverse($values, true);
}
$files = rnatsort($values);
jwhat
rsort wouldn't work, as it would not sort them numerically, ie 100 comes before 20.
Psytronic