James Oswald James Oswald - 6 months ago 21
PHP Question

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

I'm trying to figure out why

count(scandir("/dirname"));
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:

<?php
setcookie("user", count(scandir("/players")));
?>


The directory contains 2 files. But
count(scandir("/dirname"));
still evaluates to 0. Is it because the array

player0.json
player1.json


returned by
scandir()
is a non countable object?

Answer

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:

scandir(__DIR__.'/players')

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.