简体   繁体   中英

PHP increment variable with glob

New to PHP...searched the manual, just don't understand how to put it all together. I'm trying to go through a folder and display each html file as it's contents...that part works. I can't figure out how to change a div id incrementally.

This code works for displaying the what I want I just need unique id's in my divs.

$dir = realpath('./path/to/folder/of_files/');
foreach (glob($dir .'/*.html') as $page){
   $div = file_get_contents($page);  
   echo ("<div class=\"interface\" id=\"ID_$id\">$div</div>");
}

Thanks in advance.

If $id is just some integer you can stick an $id++; somewhere...

$id = 1;
$dir = realpath('./path/to/folder/of_files/');

foreach (glob($dir .'/*.html') as $page){
   $div = file_get_contents($page);  
   echo ("<div class=\"interface\" id=\"ID_$id\">$div</div>");
   $id++;
}

Do it like this:

$dir = realpath('./path/to/folder/of_files/');
$id = 1;
foreach (glob($dir .'/*.html') as $page)
{
   $div = file_get_contents($page);  
   echo ("<div class=\"interface\" id=\"ID_{$id}\">$div</div>");
   $id++; //this is just... $id = $id + 1;
}

Or, you can auto increment using foreach's AS syntax.

$dir = realpath('./path/to/folder/of_files/');
foreach (glob($dir .'/*.html') as $id => $page)
{
   $div = file_get_contents($page);  
   echo ("<div class=\"interface\" id=\"ID_{$id}\">$div</div>");
}

Note that you may want to increment $id in the 'echo' statement if you don't want $id to start at 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM