简体   繁体   中英

Store PHP variables in an array, until the loop ends

<ul>
<?php 
foreach (glob("*") as $filename) {
    ?>

  <li><a href="<?php echo $filename;?>"><?php echo $filename; ?></a></li>
<?php 
}
?>
</ul>

I get the output as

home.php
css
contact.php

An so on! My question is can I store all the $filename I get into an array?? Such as

$files=array(home.php,css,contact.php)

If i add new file I need it in an Array! I tried $files=array($filename); but it only make the last file as array!! Anyone can help?? Thanks in advance..

You need to initialize your array as blank as so:

$files=array();

Then in your loop you need to use array_push() to add the files to the array like this:

array_push($files, $filename);

Once the loop is complete, the array $files will contain all the file names.

Maybe you want to do something like this?

$filenames = array();           
$all_files = array("home.php", "css", "contact.php");

            foreach ($all_files as $filename) {
                $filenames[] = $filename;
            }

            print_r($filenames);`

Or maybe you want to add all items concatenated, separated by comma?

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