Search code examples
phparraysfilefile-exists

PHP check if file exists from array


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.


Solution

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