The way I see it, your whole process can be boiled down to this:
<label for="country">** Select Country: </label>
<?php
$countries = file('countries.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!$countries) {
echo '<input type="text" name="country" id="country" maxlength="40" size="40">';
} else {
array_unshift($countries, '');
printf(
'<select name="country" id="country"><option>' . "\n\t%s</option>\n</select>",
implode("</option>\n\t<option>", $countries)
);
}
Advise:
- Trimming your data should be done at write time (once), so that you never again need to trim your data ever again.
file()
will split your file's data line-by-line -- you can use flags to prevent newlines and empty lines (but those empty lines shouldn't be in your file to begin with).- Move all styling to an external style sheet or at the very least out of your html markup -- it just makes your code harder to read with inline styling.
- Typically,
<label>
tags include afor
attribute to connect with a field'sid
attribute. This is your choice to make. - Don't repeat the same label. More generally, don't repeat yourself.
- I recommend not declaring single-use variables. If you are concatenating just to print anyhow, then just print as you go.
- I think you will have a very hard time finding
goto
in any modern professional applications. I recommend that you skip learning about this technique because when used, it gives a code an outdated smell. Other similar opinions: What is so bad with goto when it's used for these obvious and relevant cases?, Is GOTO in PHP evil?, Is GOTO a good practice? maxlength="40" size="40"
is of no use in a<select>
-- just omit these attributes.- There is no benefit in repeating an
<option>
's text value as itsvalue
attribute -- just omit that markup bloat. - Because you just need to feed your country names to option tags, you can just
implode()
instead of using aforeach()
. It's up to you if you prefer this technique. - I am using
array_unshift()
to prepend an empty value to the array, this will provide the first empty<option>
. - Try to avoid relying on
<br>
for creating vertical space within your HTML document. Using fewer and better chosen html elements to craft your document will make it cleaner and easier to manage through styling.