1

I've noticed something interesting about PHP's glob function.

When I do

$directories = glob('*', GLOB_ONLYDIR);
echo json_encode($directories);

the function will return a bunch of folders's names in a json array, great!

But when I do

$directories = glob('./img/works/*', GLOB_ONLYDIR);
echo json_encode($directories);

the function will return a bunch of folder's names with the path like ones shown below:

[".\/img\/works\/123",
 ".\/img\/works\/234",
 ".\/img\/works\/345",
 ".\/img\/works\/456"]

Is this normal? If it is, how can I get the glob function to output only the names of the folders?

A relevant question will be: Is there a way to use GLOB_NOESCAPE GLOB_ONLYDIR flags at the same time when calling the glob function?

1 Answer 1

3

Yes the behavior is as it should be! You could do something like this if you want, to only get the dir name:

$directories = array_map("basename", glob('./test/*', GLOB_ONLYDIR));
echo json_encode($directories);

EDIT:

Yes you can use multiple flags with glob, it's that simple:

$directories = array_map("basename", glob('./test/*', GLOB_ONLYDIR | GLOB_NOESCAPE));
Sign up to request clarification or add additional context in comments.

1 Comment

Sweet! A relevant question will be: Is there a way to use GLOB_NOESCAPE GLOB_ONLYDIR flags at the same time when calling the glob function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.