1

I have a query that takes some file names from a database based on Order_ID. Many files might be associated with one order. The query looks like

$download2 = xtc_db_query("SELECT orders_products_filename FROM orders_products_download WHERE orders_id='".$last_order."'");
while ($activated2 = xtc_db_fetch_array($download2)) 
{

    $file = $activated2['orders_products_filename'];
    $pieces = explode(".zip", $file);
    print_r ($pieces);

    if(file_exists($pieces.'.zip'))
    { echo "1"; }
    if(!file_exists($pieces.'.zip'))
    { echo "2"; }

}

What I want to do is fire an action if the file exists or not. As $pieces is an array file_exists assumes the whole array is a file and it does not work (it always echoes 2). It would be great if someone gives me a hint how to fix that.

2
  • 1
    Can you var_dump($pieces) ? Does it contain only one file than you can access it by $pieces[0] or else you will need a loop. Commented Mar 25, 2014 at 13:43
  • explode will have data in array with index so passing array in file_exists() will not work u need to pass the array element not the entire array. Commented Mar 25, 2014 at 13:46

2 Answers 2

5

I think you are after something like:

foreach ($pieces as $piece) {
    if (file_exists($piece . '.zip')) {
        echo '1';
    } else {
        echo '2';
    }
}

Or perhaps run a filter on the array, to obtain a list of files that exist, such as:

$existingFiles = array_filter(
    $pieces,
    function ($piece) { return file_exists($piece . '.zip'); }
);
Sign up to request clarification or add additional context in comments.

Comments

0

file_exists(); expects absolute path, make sure you are passing absolute path.

Regarding the code i would suggest some improvements, although this is not related to the question you are asking for.

if(file_exists($pieces.'.zip')) { 
    echo "1"; 
}
if(!file_exists($pieces.'.zip')) { 
    echo "2"; 
}

you can write it as

if(file_exists($pieces.'.zip')) { 
    echo "1"; 
} else { 
    echo "2"; 
}

There is no need to call file_exists 2 times.

If your intention is to return integer values then you could try ternary operator.

echo file_exists($pieces.'.zip') ? 1 : 2;

Comments

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.