Can I make a PHP function to create text input fields?
10,326
Solution 1
You should not use any more tag inside the php
function makeTextInputField($name)
{
echo '<label for = "'.$name.'">'.ucfirst($name).'</label><input type = "text" name = "'.$name.'" />';
}
Solution 2
Your problem is that inside PHP code you're opening new PHP tags, which actually are not required. Try this function and see if it's working for you:
function makeTextInputField($name)
{
echo sprintf('<label for="%s">%s</label> <input type="text" name="%s"></input>', $name, ucfirst($name), $name);
}
Author by
kibowki
Updated on June 05, 2022Comments
-
kibowki almost 2 years
So I'm going to be making a couple forms with multiple text input boxes, so I figured making a function to help automate this would be a good idea.
Below is the function I've come up with: however, the results I've gotten seem to be really weird, being a combination of "echo" and a mess of single quotes. Does everything look correct in there? I'm new to PHP, so I'm really sorry if it's an obvious mistake I'm missing.
function makeTextInputField($name) { echo '<label for = "<?php $name ?>"> <?php ucfirst($name) ?> </label><input type = "text" name = "<?php $name?>"></input>'; }
-
Admin almost 11 yearsThe
input
tag must be closed with this syntax:<input />
. There is no need</input>
. -
elclanrs almost 11 yearsI guess people dont like
sprintf
. So sad. :( -
brasofilo over 3 years
echo sprintf()
is the same asprintf()
:) -
mickmackusa about 2 years
echo sprintf()
is an "antipattern". There is absolutely no reason that anyone should ever writeecho sprintf()
in any code for any reason -- it should beprintf()
withoutecho
every time. -
mickmackusa about 2 years
echo sprintf()
is an "antipattern". There is absolutely no reason that anyone should ever writeecho sprintf()
in any code for any reason -- it should beprintf()
withoutecho
every time.