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);
}
Share:
10,326
kibowki
Author by

kibowki

Updated on June 05, 2022

Comments

  • kibowki
    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
    Admin almost 11 years
    The input tag must be closed with this syntax: <input />. There is no need </input>.
  • elclanrs
    elclanrs almost 11 years
    I guess people dont like sprintf. So sad. :(
  • brasofilo
    brasofilo over 3 years
    echo sprintf() is the same as printf() :)
  • mickmackusa
    mickmackusa about 2 years
    echo sprintf() is an "antipattern". There is absolutely no reason that anyone should ever write echo sprintf() in any code for any reason -- it should be printf() without echo every time.
  • mickmackusa
    mickmackusa about 2 years
    echo sprintf() is an "antipattern". There is absolutely no reason that anyone should ever write echo sprintf() in any code for any reason -- it should be printf() without echo every time.