I'm building an autoloader that extends the include_path. It takes an array, appends the explode()d include path, removes all references to the current directory, adds a single current directory at the start of the array, and finally join() the whole thing back together to form a new include path. The code is listed below
<?php
static public function extendIncludePath (array $paths)
{
// Build a list of the current and new paths
$pathList = array_merge (explode (PATH_SEPARATOR, $paths), explode (PATH_SEPARATOR, get_include_path ()));
// Remove any references to the current directory from the path list
while ($key = array_search ('.', $pathList))
{
unset ($pathList [$key]);
}
// Put a current directory reference to the front of the path
array_unshift ($pathList, '.');
// Generate the new path list
$newPath = implode (PATH_SEPARATOR, $pathList);
if ($oldPath = set_include_path ($newPath))
{
self::$oldPaths [] = $oldPath;
}
return ($oldPath);
}
?>
I wanted to also use array_unique() on the array before imploding it so that PHP doesn't keep looking in the same place multiple times if someone is careless and specifies the same path more than once. However, I also need to maintain the sort order of the array because include looks in the directories in the order they're defined in the include path. I want to look in the current directory first, then my list of search directories and finally the original include path so that, for example, an old version of a common library in the default include_path doesn't get included in favour of a newer version in my search list.
For these reasons I can't use array_unique() because it sorts the array's contents.
Is there a way of getting array_unique to preserve the order of the elements in my array?
$array = array_flip(array_flip($array))an option for you? (array_flipswaps values with keys, and since keys are always unique, a doublearray_flipmakes the values in your array unique.)