12

Please note that I want the compartment number to change.

<?php
    $compartment = "1";

        /* HERE I NEED SOME SCRIPT TO FIND THE EXTENSION OF THE FILE NAME $compartment AND TO SAVE THAT AS A VARIABLE NAMED 'EXTENSION'.*/

    if (file_exists($compartment.$extension)) {
        echo "$compartment.$extension exists!
    } else {
        echo "No file name exists that is called $compartment. Regardless of extension."
    }
?>


<?php
    $compartment = "2";

        /* HERE I NEED SOME SCRIPT TO FIND THE EXTENSION OF THE FILE NAME $compartment AND TO SAVE THAT AS A VARIABLE NAMED 'EXTENSION'.*/

    if (file_exists($$compartment.$extension)) {
        echo "$compartment.$extension exists!
    } else {
        echo "No file name exists that is called $compartment. Regardless of extension."
    }
?>

Thank You!

Andy Cheeseman
  • 283
  • 1
  • 3
  • 13
  • What if there's more than one? Any way, you can use glob. – Artefacto Jul 08 '10 at 09:28
  • And what do you expect the find to do? Search in just 1 specific folder or search in all folders starting from a specific one? Does a partial match qualify or should the complete filename match? Anyways, you might want to check the [opendir](http://www.php.net/opendir) and [readdir](http://www.php.net/readdir) functions in the PHP reference – wimvds Jul 08 '10 at 09:30
  • The will only be one file with that name, so I need not worry about multiple matches. Partial matches should not be returned. I.e. I want to return 1 and 13 separately. – Andy Cheeseman Jul 08 '10 at 10:44

2 Answers2

28

You need glob().

$compartment = "2";

$files = glob("/path/to/files/$compartment.*"); // Will find 2.txt, 2.php, 2.gif

// Process through each file in the list
// and output its extension
if (count($files) > 0)
foreach ($files as $file)
 {
    $info = pathinfo($file);
    echo "File found: extension ".$info["extension"]."<br>";
 }
 else
  echo "No file name exists called $compartment. Regardless of extension."

by the way, what you are doing above is crying for a loop. Don' repeat your code blocks, but wrap one of them into this:

 $compartments = array(1, 3, 6, 9); // or whichever compartments 
                                    // you wish to run through

 foreach ($compartments as $compartment)
  {
   ..... insert code here .......
  }
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • Thanks. I will need to reference the 'recovered' file a couple of time within the code. Will this be a problem? – Andy Cheeseman Jul 08 '10 at 10:46
  • @Andy no, as long as you're doing it inside the `foreach $files as $file` loop. (You can also use the variable outside of it but then you have to pick which one.) – Pekka Jul 08 '10 at 10:47
5

Look up:

  • glob — Find pathnames matching a pattern
  • fnmatch — Match filename against a pattern
  • pathinfo — Returns information about a file path
w3spi
  • 4,380
  • 9
  • 47
  • 80
Gordon
  • 312,688
  • 75
  • 539
  • 559