Search code examples
phpincludeechofile-exists

PHP. How to automatically include all existed files and get a variable data?


I need help with includes in PHP.

I have a group of files where each contains a variable $tariff_about.

<?php               
    include("tariffs/tariff-a1.php"); echo $tariff_about;
    include("tariffs/tariff-a2.php"); echo $tariff_about;
    include("tariffs/tariff-a3.php"); echo $tariff_about;
    include("tariffs/tariff-a4.php"); echo $tariff_about;
    include("tariffs/tariff-a5.php"); echo $tariff_about;
;?>

It would be nice to automatically include all existed files with 'tariff-a' prefix.

I understand that there is PHP file_exists function; however, I don't know how to make it work in this example with echo.

Help me, please.


Solution

  • Use glob to get all the files matching a certain pattern, then loop and include.

    $files = glob( 'tariffs/tariff-a*.php' );
    
    foreach( $files as $file ) {
        include( $file );
    }