James Oswald James Oswald - 1 year ago 63
PHP Question

Is the array returned by scandir() a countable object?

I'm trying to figure out why

always evaluates to 0 when the number of files in the directory is not 0. When a person goes onto my page, the following script executes at the top of the page:

setcookie("user", count(scandir("/players")));

The directory contains 2 files. But
still evaluates to 0. Is it because the array


returned by
is a non countable object?

Answer Source

Assuming the directory players is located in the same directory where the PHP file is located, you can simply pass 'players' to scandir() or other function that works with directories. It is a relative path and most of the times it works.

But, in order to make sure your code always works, you better use the PHP magic constant __DIR__ to generated the full path of the players directory:


should return an array that contains the names of the files stored in the players directory and passing this array to count() will correctly return the number of values it contains (as it also does now).

To answer the question in the title, on success scandir() returns a PHP array and the PHP arrays are always countable.