Home > Blockchain >  Create html dropdown from php array in other file
Create html dropdown from php array in other file

Time:03-09

I have a php file which creates an array. I would like to access that array from another php file. I would then like to create an html dropdown with the options being the values of the array. This is the array in the first php file (called hi2.php)

<?php
$toReturn = array();
while ($row = pg_fetch_row($ret)) 
{
    $c_row = current($row);
    array_push($toReturn, "<option value=" . "'" . $c_row . "'" . ">" . $c_row .  "</option>");

}
return($toReturn);
?>

This is the html in the second php file to create a dropdown using the array from the first file(hi2.php)

<label for="column1">Variable for Column 1: </label>
            <br>
            <select name="column1" id="column1">
                <?php
                $vars = include 'hi2.php';
                foreach($vars as $item){
                    echo "<option value='strtolower($item)'>$item</option>";
                }
                ?>
            </select>
     <input type="submit" value="Submit">

I am currently getting this error Parse error: syntax error, unexpected 'foreach' (T_FOREACH)

CodePudding user response:

seems you forgot to complete {} of foreach

<?php
     $vars = include 'hi2.php';
     foreach($vars as $item){
        echo "<option value='strtolower($item)'>$item</option>";
     }
?>

use return in hi2.php instead of print_r.
$vars = include 'hi2.php'; this assign return value of hi2.php to $var.
see Example #5 in the documentation for include.

and add ; in hi2.php after return $toreturn

CodePudding user response:

You're using include incorrectly. If you're going to use hi2.php to return data, you need to do it inside a function:

<?php
function doIt() {
  $toReturn = array();
  while ($row = pg_fetch_row($ret)) 
  {
      $c_row = current($row);
      array_push($toReturn, "<option value=" . "'" . $c_row . "'" . ">" . $c_row .  "</option>");
  }
  return($toReturn);
}
?>

(You could also omit the function and simply use $toReturn as the returned value, but that's not recommended because it creates a global variable. Better to have a function return a value and assign that value to a variable in your 2nd file.)

Then you can use it in your 2nd file like this:

<label for="column1">Variable for Column 1: </label>
        <br>
        <select name="column1" id="column1">
            <?php
            include 'hi2.php';
            $vars = doIt();
            foreach($vars as $item){
                echo "<option value='strtolower($item)'>$item</option>";
            }
            ?>
        </select>
 <input type="submit" value="Submit">
  • Related