March 3, 2013

php array to radio button

Question by user2128593

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.

Answer by Starx

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

foreach($files as $key => $value) {
    //....
}
March 12, 2012

dynamically creating array in php

Question by vaichidrewar

I am trying to create arrays dynamically and then populate them by constructing array Names using variable but I am getting the following warnings

Warning: in_array() expects parameter 2 to be array, null given
Warning: array_push() expects parameter 1 to be array, null given

For single array this method worked but for array of arrays this is not working. How should this be done?

<?php

for ($i = 1; $i <= 23; ++$i) 
{
        $word_list[$i] = array("1"); 
}


for ($i = 1; $i <= 23; ++$i) 
{
  $word = "abc";
  $arrayName = "word_list[" . $i . "]";
  if(!in_array($word, ${$arrayName})) 
  {
    array_push($$arrayName , $word);
  }
}


?>

Answer by Aleks G

Why are even trying to put array name in a variable and then de-reference that name? Why not just do this:

for ($i = 1; $i <= 23; ++$i) 
{
  $word = "abc";
  $arrayName = "word_list[" . $i . "]";
  if(!in_array($word, $word_list[$i])) 
  {
    array_push($word_list[$i] , $word);
  }
}

Answer by Starx

And in the for loop, you are accessing the array the wrong way

Here is your corrected code

for ($i = 1; $i <= 23; ++$i) 
{
  $word = "abc";
  $arrayName = $word_list[$i];
  if(!in_array($word, $arrayName)) 
  {
    array_push($arrayName , $word);
    $word_list[$i] = $arrayName;
  }

}
...

Please fill the form - I will response as fast as I can!