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.

有帮助吗?

解决方案

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'); }
);

其他提示

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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top