Page 1 of 1

function

Posted: Mon Dec 12, 2011 1:20 pm
by fuzznut
I have created a function that accepts two arguments a first and a last name. the function returns the initials in a single string. I need to call the above function 5 times, passing in 5 different names and print the value returned each time. I can't figure out how to loop the function 5 times so the user can enter a different name each time and it print out each of the five names' initials. here's what i have so far.
index.php

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Functions!</title>
</head>
<body>
<p>Please enter your first and last name so I can 
give you your initials.</p>

	<form action="functions.php" method="post">
	<p>First Name: <input type="text" name="first_name" size="20" /></p>
	<p>Last Name: <input type="text" name="last_name" size="20" /></p>
	<input type="submit" name="submit" value="Get My Initials" />
	</form>
	
	
</body>
</html>
functions.php

Code: Select all

<?php

function first_and_last($first_name, $last_name ) {
    return $first_name[0] . '. ' . $last_name[0] . '.';

	}
echo first_and_last($_POST['first_name'], $_POST['last_name']);
?>

Re: function

Posted: Mon Dec 12, 2011 1:36 pm
by Celauran
Rather than having the form action point to functions.php, I'd have it point to itself (or just leave it blank) and have the page execute the function whenever the form is submitted.

Code: Select all

<?php

function first_and_last($first_name, $last_name )
{
    return $first_name[0] . '. ' . $last_name[0] . '.';
}

if (isset($_POST['first_name']) && isset($_POST['last_name']))
{
    echo first_and_last($_POST['first_name'], $_POST['last_name']);
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Functions!</title>
</head>
<body>
<p>Please enter your first and last name so I can 
give you your initials.</p>

        <form action="functions.php" method="post">
        <p>First Name: <input type="text" name="first_name" size="20" /></p>
        <p>Last Name: <input type="text" name="last_name" size="20" /></p>
        <input type="submit" name="submit" value="Get My Initials" />
        </form>
        
        
</body>
</html>