0

Well,

I have a script, that checks if one of the files in the array exists or not.

But now I don't know how to get the file, from the array that doesn't exist. Here's an example:

<?php
$files = [
   "user/important.ini",
   "user/really_needed.php"
];

if(file_exists($files) == false) {
   $data = "1";
   $meta = array(
       "file" => ????,
       "error" => "Missing file"
    );

?>

So I'd like to "replace" the "????" with the file that doesn't exists, since I don't know how to get this file, it's those question marks.

Is there possible code I could use, to get the file that doesn't exist?

1
  • file_exists takes a string (filename) not an array. You will have to loop over your filenames in $files. In case the check fails for a certain file, you will have its name right there in the loop. Commented Jun 3, 2020 at 12:04

2 Answers 2

2

file_exists() expects a file name and if you use an array (as you currently do) you should get a warning...

Warning: file_exists() expects parameter 1 to be a valid path, array given

This assumes that you want all of the files that don't exist and keeps a list of the failures. It uses foreach() over the array and tests each item, adding it to the list if it doesn't exist using $meta[] (don't forget to initialise this array before the loop) ...

$files = [
        "user/important.ini",
        "user/really_needed.php"
];
$meta = [];
foreach ( $files as $file ) {
    if(file_exists($file) == false) {
        $data = "1";
        $meta[] = array(
                "file" => $file,
                "error" => "Missing file"
        );
    }
}

print_r($meta);
Sign up to request clarification or add additional context in comments.

Comments

1

Looping over the files to check if they exist is one way this could be done. I suggest using a foreach loop here.

<?php
$files = [
   "user/important.ini",
   "user/really_needed.php"
];

$meta = [];
foreach ($files as $file) {
   if(!file_exists($file) {
      $data = "1";
      $meta[] = array(
         "file" => $file,
         "error" => "Missing file"
      );
?>

2 Comments

There is an error in your code. $meta will only hold the last missing file. Add [] to the variable name.
Right, forgot he was checking multiple files. Thanks for the heads up <3

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.