I'm trying to get the name of a file in php, but I'm iterating through an array of files so I don't have the exact path... unless there is a method inside the file that returns the name of the file (or the path, in which I can use basename()
), which I haven't been able to find. My code looks like this:
foreach ($myfiles as $myfile) {
// Get name of $myfile here. (Technically as a string)
if ($myfilename == "Something) {
// Do something
}
}
I am trying to find the name of the file ($myfile
) so I can manipulate it as if it were a string.
Getting the name of file in PHP is not what I'm looking for, as all the answers imply you have a path, which I do not.
Basically the php equivalent of Java's: File.getName()
Thank you.
CodePudding user response:
The method that you are looking for is pathinfo.
It returns an array with information about the file, the filename
index has the name of the file.
CodePudding user response:
Do you need like this?
$file = fopen("File.txt", "r");
// $filename = $file->name; // no way
There is no method for PHP.
Try this way:
<?php
$myfiles = [];
$files = ['fileA.txt', 'fileB.txt'];
foreach($files as $filename) {
$myfiles[] = ['file' => fopen($filename, "r"), 'filename' => $filename];
}
foreach ($myfiles as $myfile) {
if ($myfile['filename'] == "Something") {
// Do something
}
}
?>