Search code examples
phparraysradio-buttondynamic-arrays

php array to radio button


i want to create a radio button labeled with the values of my array. all i can do is to print them all. what can i use to access my array (dynamic-array) besides indexes since i will not know the order and number of files inside my languages directory? Thanks!

input

english.xml,mandarin.xml,french.xml

these files is saved at languages and i will use the file names as labels in my radio button form.

$files = glob("languages/*.xml");

foreach($files as $file){

   $file = substr($file, 10); //removes "languages/"
   $file = substr_replace($file, "", -4); //removes ".xml"
   ?>

   <p><?=$file?></p> // prints out the filename
   <?}?>

output

<form action="">
<input type="radio" name="lang" value="english">english
<input type="radio" name="lang" value="mandarin">mandarin
<input type="radio" name="lang" value="french">french
</form>

sorry for my bad english i hope i explained it well.


Solution

  • Using [] you can add elements to an array. The order will be the order you've placed them in, which is the same as the $files array you're looping through.

    The pathinfo function can get the name of a file (without directory or extension).

    function getLangs() {
        $langs = array();
        $files = glob("languages/*.xml");
    
        foreach($files as $file) {
            $lang = pathinfo($file, PATHINFO_FILENAME);
            $langs[] = $lang;
        }
    
        return $langs;
    }
    

    Now print it using

    $langs = getLangs();
    
    foreach ($langs as $lang) {
       echo "<label><input type='radio' name='lang' value='$lang' /> $lang</label>";
    }
    

    Instead of using echo you could build up a template like

    <form action=''>
    <?php foreach ($langs as $lang): ?>
       <label><input type="radio" name="lang" value="<?= $lang ?> /> value="<?= $lang ?></label>
    <?php endforeach; ?>
    </form>