1

I have a big piece of php code that builds a dropdown menu and I want to minimize it by loading the select options from a text file. How to do this in the right way with php?

An example of original code:

$field['options'] = array(
    array('value' => 'Anenii Noi', 'text' => 'Anenii Noi', 'depth' => 0),
    array('value' => 'Bălţi', 'text' => 'Bălţi', 'depth' => 0),
    array('value' => 'Basarabeasca', 'text' => 'Basarabeasca', 'depth' => 0),
    ....
    array('value' => 'Ungheni', 'text' => 'Ungheni', 'depth' => 0)
);

And this is what I try to do, but without success:

// read a text file with select options
// where each option is a seperate line
$file_array = str_replace("\n","", file($file_path));

// build the list of arrays with select options
foreach ($file_array as $location)
    $options .= "array('value' => '" . $location . "', 'text' => '" . $location . "', 'depth' => 0),";

foreach($form['field'] as $k => $field) {

    // replace the big list of arrays with $options variable
    $field['options'] = array($options);

    $form['field'][$k] = $field;
    break;
}
2
  • 1
    Instead of using a text file (which I don't recommend) you can simply put all those options to a separate php file and include it where you need them.. Commented Nov 24, 2015 at 14:05
  • @matei-mihai I need to keep the options list as a pure text file because I want to use it in two separate functions that works differently and I can't change this. But, probably, I must to think about this. Commented Nov 24, 2015 at 14:16

1 Answer 1

1

Looks like you had it almost. But you tried to mimic the pure php code, that might have worked if you use eval() later on, but you need to mimic its functionality.

// read a text file with select options
// where each option is a seperate line
$file_array = str_replace("\n","", file($file_path));

// build the list of arrays with select options
$options = array();
foreach ($file_array as $location) {
    $options[] = array('value' => $location, 'text' => $location, 'depth' => 0);
}

foreach($form['field'] as $k => $field) {

    $field['options'] = $options;

    $form['field'][$k] = $field;
    break;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I got these notices: Notice: Undefined index: value ... and Notice: Undefined index: text ...
oh, $field['options'] = array($options); that line should be now $field['options'] = $options;
Great! This was the problem! Now the code works. Thank you very much!

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.