PHP | glob() Function

PHP glob() Function


Hello folks! welcome back to a new edition of our tutorial on PHP. In this tutorial guide, we are going to be studying about the PHP glob() Function.

The built-in PHP glob() function returns an array containing file names or directories matching the specified pattern.

Syntax

Following below is the syntax to use this function -

array glob ( string $pattern [, int $flags = 0 ] )


This built-in function searches for the path names matching the patterns according to rules used by the glob() function, which is similar to rules used by common shells.

Return Value

It returns an array containing the matching files and directories on success or false on failure.

Example1

Try out the below example -

<?php
   print_r(glob("/PhpProject/php/*.txt"));
?>

Output

When the above code is executed, it will produce the following result -

Array
(
    [0] => /PhpProject/php/phptest1.txt
    [1] => /PhpProject/php/phptest2.txt
    [2] => /PhpProject/php/phptest3.txt
    [3] => /PhpProject/php/phptest4.txt
    [4] => /PhpProject/php/phptest5.txt
    [5] => /PhpProject/php/phptest6.txt
    [6] => /PhpProject/php/phptest7.txt
    [7] => /PhpProject/php/phptest8.txt
    [8] => /PhpProject/php/phptest9.txt
    [9] => /PhpProject/php/phptest10.txt
)

Example2

Try out the below example -

<?php
   foreach(glob("/PhpProject/php/*.txt") as $filename) {
      echo "$filename size " . filesize($filename) . "\n";
   }
?>

Output

When the above code is executed, it will produce the following result -

/PhpProject/php/phptest1.txt size 223
/PhpProject/php/phptest2.txt size 254
/PhpProject/php/phptest3.txt size 275
/PhpProject/php/phptest4.txt size 214
/PhpProject/php/phptest5.txt size 269
/PhpProject/php/phptest6.txt size 235
/PhpProject/php/phptest7.txt size 287
/PhpProject/php/phptest8.txt size 298
/PhpProject/php/phptest9.txt size 209
/PhpProject/php/phptest10.txt size 265


Alright guys! This is where we are going to be rounding up for this tutorial post. In our next tutorial, we are going to be discussing about the PHP is_dir() Function.

Do feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.