0

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.

2
  • Its really hard to understand, what you want? Could be please show the input array and output you want? Commented Mar 3, 2013 at 10:45
  • Ok, so what does echo $file give you? Commented Mar 3, 2013 at 11:18

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Note that it isn't required to use a function, but it's good practice to separate the do from the view.
0

You can access the key of the array using foreach too. Like this:

foreach($files as $key => $value) {
    //....
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.