0

In the function below, I'm seeing to sort the array by alpha. However, it returns bool(true) rather than the actual sorted array. What am I missing?

function get_dirs($dir) {
    $array = array();
    $d = dir($dir);
    while (false !== ($entry = $d->read())){
        if($entry!='.' && $entry!='..') {
            $entry2 = $dir."/".$entry;
            if(is_dir($entry2)) {
                $array[] = $entry;
            }
        }
    }
    $d->close();
    //return $array; THIS WORKS FINE BUT UNSORTED
    return natcasesort($array); //THIS RETURNS A BOOLEAN?
    }
1
  • Yes, because it returns a boolean! php.net/natcasesort Commented Nov 22, 2011 at 15:59

4 Answers 4

3

natcasesort returns TRUE on success or FALSE on failure.

Change

return natcasesort($array);

to

natcasesort($array);
return $array;
Sign up to request clarification or add additional context in comments.

Comments

2

That function returns TRUE/FALSE on success/failure. The original variable will be sorted.

$d->close();
if(natcasesort($array)) return $array;
else return false;

Check out the documentation here: http://php.net/manual/en/function.natcasesort.php

Comments

2

Yes. As the manual says:

Returns TRUE on success or FALSE on failure.

Have a look at the function signature in the manual page:

bool natcasesort ( array &$array )

The & sign means "reference", so $array is modified, rather than a new array being returned. This is the same as all (IIRC) PHP sorting functions.

You should do the sort and then return $array:

natcasesort($array);
return $array;

Comments

1

natcasesort sorts the array and returns true on success and false if it fails. Solve it by sorting the array and then returning it.

natcasesort($array);
return $array;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.