简体   繁体   中英

array_unique() without sorting

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?

Not using array_unique() directly; but array_unique does preserve the keys, so you can do a ksort() afterwards to recreate the original order of entries

you may also use array_count_value. you will get your unique array result at key of your function result

its doesn't break your array sort content.

reference : http://php.net/manual/en/function.array-count-values.php

Something like:

$temp = array();

foreach ( $original_array as $value ) {
    $temp[$value] = 1;
}

$original_array = array_keys($temp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM