Jump to content

Help turning code into functions


webdevdea
 Share

Recommended Posts

I need some help turning code into functions, I am getting my page to do as it should but its not with functions

$confId = rand(1,1000);

I need for this to be a function

as well as this 

if($base == "")
	{	$errors .= "<li>How Many Days Are You Attending the Convention?</li><br />";
	}
	if($base == "One") 
	{	$cost = 100;} 
	if ($base == "One" && $mealPlan =="Yes")
	{ $cost = 100 + 50;
	}
	
	if($base == "Two" )
	{	$cost = 175;}
	if ($base == "Two" && $mealPlan =="Yes")
	{ $cost = 175 + 75;
	}
	
	
	
	if($base == "Three")
	{	$cost = 225;}
	if ($base == "Three" && $mealPlan =="Yes")
	{ $cost = 225 + 100;
	}

	
	

$count = count($extra);
	// If no errors, display the form data
	if($errors == "")
	{
echo <<<END
	<p>$first_name $last_name thank you for your interest.</p>
	<p>You have registered for $base day(s) at our Technology Conference</p>
	<p> You choose  $track as for your track of interest.</p>
	<p>Please bring cash or your credit card the first day for payment.</p>
	<p> your Confirmation number is $confId</p>
	<p> Your total cost including your meal plan option is$$cost</p>
	<p> We look forward to your participation</p>
   
	<ul>
END;



echo <<<END
	</ul>
	
END;
	}
	else						// If errors, display errors
	{
		errorMessage($errors);
	}

Thank alot for the help 

Link to comment
Share on other sites

Actually the sample provided in the prev post is a little off. It should read:

function rand_string(&$confide)

in the header in order to return the value as the creator designed it.

 

More importantly though - the one-line function that you want is really meaningless and less efficient than just executing the one-line inline in your code. Why would you want to make a function out a simple statement that has no variable in it?

 

As for making anything a function - functions are great when you have a set of code that either:

a) gets used repeatedly

or

b) gets used repeatedly with different variables involved that change the result

 

Looking at the code you presented for your second function, I'm wondering how many times you are going to call it. But - if you really want to do it, simple wrap all the code in a set of curly braces with a line on top of that saying:

function (myfunctionname)(my vars, my vars....)

 

where 'my vars' are values you send in to the function to be used in whatever task it is performing for you. If you have none, then you won't need to include these in the function header.

 

The manual covers writing your own functions. You should look it up.

Link to comment
Share on other sites

The manual ( TEXTBOOK) that we are required to have did not cover this just yet and I have read ahead two chapters and still nothing, Im doing some online research to try and figure it out. as for the one line function I am to have two functions and that was going to be one, I know its a cheap way out but I have the code doing exactly what its supposed to do without the functions and since it was not clearly covered and given to us as a mission almost impossible, Im trying to stick some functions in there somewhere as long as there are two, he did not say how complicated they needed to be. Thanks for the information, Im going to work on this some more and post my findings 

Link to comment
Share on other sites

I have created the functions to show you how, but I do not know what you are wanting with some of the code.

This code is where I am unclear because I do not know where you are getting $extra from

$count = count($extra);
	// If no errors, display the form data
	if($errors == "")
	{
echo <<<END
	<p>$first_name $last_name thank you for your interest.</p>
	<p>You have registered for $base day(s) at our Technology Conference</p>
	<p> You choose  $track as for your track of interest.</p>
	<p>Please bring cash or your credit card the first day for payment.</p>
	<p> your Confirmation number is $confId</p>
	<p> Your total cost including your meal plan option is$$cost</p>
	<p> We look forward to your participation</p>
   
	<ul>
END;



echo <<<END
	</ul>
	
END;
	}
	else						// If errors, display errors
	{
		errorMessage($errors);
	}

Here are you other functions... I think it is what you are looking for, sorry if its not.

function confID( ){
    return rand(1, 1000);
}
function findCost($base, $meal = false){
    
    if(!is_bool($meal))
        $meal = $meal == 'Yes' ? true : false;
    
    $prices = array(
            "One"   => 100,
            "Two"   => 175,
            "Three" => 225
            );
    $meals = array(
            "One"   => 50,
            "Two"   => 75,
            "Three" => 100
            );
    $cost = $meal ? $prices[$base] + $meals[$base] : $prices[$base];
    
    return $cost;
}

//you can call the confID
$confID = confID( );

//you can call the find cost function
//example 1
$base = 1;
$meal = 'Yes';
$cost = findCost($base, $meal);
//you result would be 150;

//example 2
$base = 2;
$cost = findCost($base);
//your result would be 175
Link to comment
Share on other sites

Here is just one example of how you could turn this into functions. Also your confirmation number generation is wrong since simply generating a random number does not mean they are unique. You will need to keep track of these numbers and maybe instead use the auto-generated ID?

 

function PrintMessage($firstName, $lastName, $totalDays, $confName, $track, $cfmNbr, $inclMealPlan, $cost)
{
    $text = '
    {first_name} {last_name} thank you for your interest.
    
    You have registered for {total_days} day(s) at our {conference_name}.
    
    You chose {interest_track} as for your track of interest.
    
    Please bring cash or your credit card the first day for payment.
    
    Your confirmation number is {confirmation_number}.
    
    Your total cost {incl_meal_plan} is ${cost}.
    
    We look forward to your participation.
    ';
    
    $vars = array(
        '{first_name}'          => $firstName,
        '{last_name}'           => $firstName,
        '{total_days}'          => $totalDays,
        '{conference_name}'     => $confName,
        '{interest_track}'      => $track,
        '{confirmation_number}' => $cfmNbr,
        '{incl_meal_plan}'      => ($inclMealPlan) ? '(incl. your meal plan)' : '',
        '{cost}'                => $cost,
    );
    
    $text = str_replace(array_keys($vars), $vars, $text);
    $text = nl2br($text);
    
    return $text;
}

function GenerateConfirmationNumber()
{
    return mt_rand(1, 1000);
}

function CalculateCost(Array $dayPrices, Array $mealPrices, $totalDays, $inclMeals = false)
{
    if (!isset($dayPrices[$totalDays])) {
        return false;
    }
    
    if ($inclMeals && !isset($mealPrices[$totalDays])) {
        return false;
    }
    
    $basePrice = $dayPrices[$totalDays];
    
    if ($inclMeals) {
        $basePrice += $mealPrices[$totalDays];
    }
    
    return $basePrice;
}
Link to comment
Share on other sites

Here is just one example of how you could turn this into functions. Also your confirmation number generation is wrong since simply generating a random number does not mean they are unique. You will need to keep track of these numbers and maybe instead use the auto-generated ID?

 

function PrintMessage($firstName, $lastName, $totalDays, $confName, $track, $cfmNbr, $inclMealPlan, $cost)
{
    $text = '
    {first_name} {last_name} thank you for your interest.
    
    You have registered for {total_days} day(s) at our {conference_name}.
    
    You chose {interest_track} as for your track of interest.
    
    Please bring cash or your credit card the first day for payment.
    
    Your confirmation number is {confirmation_number}.
    
    Your total cost {incl_meal_plan} is ${cost}.
    
    We look forward to your participation.
    ';
    
    $vars = array(
        '{first_name}'          => $firstName,
        '{last_name}'           => $firstName,
        '{total_days}'          => $totalDays,
        '{conference_name}'     => $confName,
        '{interest_track}'      => $track,
        '{confirmation_number}' => $cfmNbr,
        '{incl_meal_plan}'      => ($inclMealPlan) ? '(incl. your meal plan)' : '',
        '{cost}'                => $cost,
    );
    
    $text = str_replace(array_keys($vars), $vars, $text);
    $text = nl2br($text);
    
    return $text;
}

function GenerateConfirmationNumber()
{
    return mt_rand(1, 1000);
}

function CalculateCost(Array $dayPrices, Array $mealPrices, $totalDays, $inclMeals = false)
{
    if (!isset($dayPrices[$totalDays])) {
        return false;
    }
    
    if ($inclMeals && !isset($mealPrices[$totalDays])) {
        return false;
    }
    
    $basePrice = $dayPrices[$totalDays];
    
    if ($inclMeals) {
        $basePrice += $mealPrices[$totalDays];
    }
    
    return $basePrice;
}
could you tell me what I need to add and take away? 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">

<style>

body
{
background-image:url('expo.tiff');
background-repeat:no-repeat;
background-position:right top;
margin-right:200px;
background-color:green;
color:black;
font-size:20px;

}
h1
{
color:orange;
text-align:center;
font-size:30px;

}
p
{

font-family:"Times New Roman";
font-size:20px;

}
</style>

<title> MAJOR PROJECT 1</title>

</head>
<body>
<p>
Please fill out the following information to register for the Conference.</p>
 <form action="http://localhost/Assignments php class/Major Project 1/function.php" method="post">
   	<table  width="750" border="0" cellpadding="0" cellspacing="0"> 
		<table  width="750" border="0" cellpadding="0" cellspacing="0"> 
		  <tr>
			<td width="88">First name: </td>
			<td width="662"><input type="text" id="first_name" name="first_name" size="30" maxlength="20" /></td>
		  </tr>
		  <tr>
			<td>Last name: </td>
			<td><input type="text" id="last_name" name="last_name" size="30" maxlength="20" /></td>
		  </tr>
		   <tr>
			<td>Address: </td>
			<td><input type="text" id="add_ress" name="add_ress" size="30" maxlength="40" /></td>
		  </tr>
		   <tr>
			<td>Company: </td>
			<td><input type="text" id="com_pany" name="com_pany" size="30" maxlength="20" /></td>
		  </tr>
		    <tr>
			<td>Email Address: </td>
			<td><input type="text" id="email" name="email" size="30" maxlength="40" /></td>
		  </tr>
		  
		  <tr>
			<td>Phone: </td>
			<td><input type="text" id="phone" name="phone" size="30" maxlength="15" /></td>
		  </tr>
	</table>
	 <select name = "track">
    <option value = "PROGRAMMING TRACK">PROGRAMMING TRACK</option>
    <option value = "NETWORKING TRACK">NETWORKING TRACK</option>
    <option value = "SECURITY TRACK">SECURITY TRACK</option>
    <option value = "WEB TRACK">WEB TRACK</option>
  </select>
  <br />
  
		<p>How Many Days Will Your Attend Conference:<br>
		  <input type="checkbox" id="One" name="base" value="One"> <label for="one">One Day</label><br />
		  <input type="checkbox" id="Two" name="base" value="Two"> <label for="two">Two Day</label><br />
		  <input type="checkbox" id="Three" name="base" value="Three"> <label for="three">Three Day</label><br />
		
		  
		  
		</p>
		
	<fieldset>
 Please Check If you would Like The Meal Plan Added to your total. 
    <input type="checkbox" name="mealPlan" value="Yes" />
<br />
<br />
		<p>
		 <input type="image" src="registernow.tiff" name="image" width="120" height="30"><br />
		
		</p>
		
  </form>
</body>
</html>

Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.