Jump to content

Recommended Posts

Im after a little advise for a couple of things.

Firstly how should I write in php $a+$b+$c+$d+$e+$f+$g+$h+$i+$j+$k+$l+$m+$n+$o+$p without having to type out any variables other than a and P?

 

eg. $total=$a thru to $p

 

Secondly when writing the code below (especially in the treetype if/elseif) I was wondering if there is a better method, perhaps using an array or function that sombody can reccommend (would this invole a list of trees and a list of values, or possibly mysql)?

 

<html>
<?php
$swordtype = $_REQUEST['swordtype'];
if 	($swordtype =="wood") 	{$a=20;} 
elseif 	($swordtype =="bronze")       {$a=40;}
elseif 	($swordtype =="iron") 	{$a=60;}
elseif 	($swordtype =="steel") 	{$a=80;}

$armourtype = $_REQUEST['shieldtype'];
if 	($armourtype =="wood") 	{$b=20;} 
elseif 	($armourtype =="bronze")      {$b=40;}
elseif 	($armourtype =="iron") 	{$b=60;}
elseif 	($armourtype =="steel")         {$b=80;}

$treetype = $_REQUEST['treetype'];
if 	   ($treetype =="alder") {$c=10;}
elseif          ($treetype =="apple") {$c=14;}
elseif           ($treetyoe =="crab apple") {$c+11;}

/*
CONTINUE THE ABOVE CODE WITH THE FOLLWING TREE TYPES;		
Ash			
Birch			
Beech			
Box			
Cherry			
Plum			 
Blackthorn		
Elm			
Hawthorn		 
Hornbeam		 
Holly			
Juniper		
Lime			
Maple			
Oak			
Pine			
Scots Pine		
Aspen 			
Poplar			
Rowan			
Whitebeam		
Sorbus			
Strawberry		
Willow			
Yew	*/
?>
</html>

You can sum the values using an array, a foreach() loop and variable variables.

 

$a = 3; $b = 5; $f = 10; $l = 22; // test data
$array = range( 'a', 'p' );
$sum = 0;
foreach( $array as $v ) {
if( !empty($$v) ) {
	$sum += $$v;
}
}
echo $sum; // Returns 40

A) See the following thread for how you would use 'lookup' arrays to map one value to another - http://www.phpfreaks.com/forums/index.php?topic=337702.0

 

B) You should also use an array to hold the resulting values, with associative key names that indicate the purpose of the value, rather than $a, $b, ... You can then use array_sum to get the sum of the values.

 

C) You should not use $_REQUEST if possible. Use the correct $_POST or $_GET or $_COOKIE variable where the data is coming from.

 

D) You should validate all your external data so that your code behaves in an expected way when the data is not present or when it does not have an expected value.

A) See the following thread for how you would use 'lookup' arrays to map one value to another - http://www.phpfreaks.com/forums/index.php?topic=337702.0

 

B) You should also use an array to hold the resulting values, with associative key names that indicate the purpose of the value, rather than $a, $b, ... You can then use array_sum to get the sum of the values.

 

C) You should not use $_REQUEST if possible. Use the correct $_POST or $_GET or $_COOKIE variable where the data is coming from.

 

D) You should validate all your external data so that your code behaves in an expected way when the data is not present or when it does not have an expected value.

 

Yeah, if the variable names were more descriptive, I might have figured out what the OP was really trying to do. You're right, this whole thing could be streamlined with arrays.

Hello, im learning somthing new here.

Ive tried a couple of things (to start with) that were mentioned in my replies below.

I get a returned value of 0, so Im doing somthing wrong.

 

Any advice on the correct syntax here.

Thankyou for your patience.

 

 

<?php

$swordtype = $_GET['swordtype'];

$swordtype = array(

'wood' => '$a=10',

'bronze'                 => '$a=20',

'iron' => '$a=30',

'steel'                 => '$a=40');

 

$armourtype = $_GET['shieldtype'];

$armourtype = array(

'wood' => '$b=10',

'bronze'                 => '$b=20',

'iron' => '$b=30',

'steel'                 => '$b=40');

 

$treetype = $_GET['treetype'];

$treetype = array (

'alder' => '$c=10',

'apple' => '$c=14',

'crab apple'=> '$c=11');

 

$number1=$a;

$number2=$b;

$number3=$c;

 

$total= $number1 + $number2 + $number3;

 

echo $total;

?>

I would do something like this -

<?php

// define the arrays that associate the keywords to the values ...
$swordtype['wood'] = 20;
$swordtype['bronze'] = 40;
// other data here...

$shieldtype['wood'] = 20;
$shieldtype['bronze'] = 40;
// other data here...

$treetype['alder'] = 10;
$treetype['apple'] = 14;
// other data here...

$items = array(); // data associated with each item
$items['swordtype'] = array('legend'=>'Sword','values'=>$swordtype); // The legend is used when printing user messages, form field legends... The values is the array of keyword/value
$items['shieldtype'] = array('legend'=>'Shield','values'=>$shieldtype);
$items['treetype'] = array('legend'=>'Tree','values'=>$treetype);

$errors = array(); // keep track of any validation errors
$result = array();

foreach($items as $key => $record){
if(empty($_GET[$key])){
	// empty
	$errors[] = "The {$record['legend']} type is empty!";
	// or you could set a default value here...
} else {
	// something was submitted, check if a valid keyword
	if(!isset($record['values'][$_GET[$key]])){
		// keyword doesn't exist
		$errors[] = "The {$record['legend']} type: {$_GET[$key]}, doesn't exist!";
		// or you could set a default value here...
	} else {
		// keyword exists, get the value
		$result[$key] = $record['values'][$_GET[$key]];
	}
}
}

if(empty($errors)){
// no validation errors, use the submitted data here...
$total = array_sum($result);
echo "Your total is: $total!";
}

// display any errors
if(!empty($errors)){
echo "The following errors occurred-<br />";
foreach($errors as $error){
	echo "$error<br />";
}
}
?>

Thank you very much, Ive tried somthing like below, however if on my html form I selected Alder and 10to12,

then I would want a value 21 returned.  Whereas at the moment my value is 2.  Is this because the number of results

are being counted instead?  Many thanks for your help.

 

<?php
$treetype = $_GET["treetype"];
$treetype['alder'] = 10;
$treetype['apple'] = 14;
$girthsize = $_GET["girthsize"];
$girthsize['10to12'] = 11;
$girthsize['12to14'] = 13;

$items = array(); 
$items['treetype']  = array('legend'=>'treetype','values'=>$treetype);
$items['girthsize'] = array('legend'=>'girthsize','values'=>$girthsize);
$errors = array(); 
$result = array();
foreach($items as $key => $record)
{	
if(empty($_GET[$key]))
{				
$errors[] = "The {$record['legend']} type is empty!";
}
else  
	{				
if(!isset($record['values'][$_GET[$key]]))
		{					
$errors[] = "The {$record['legend']} type: {$_GET[$key]}, doesn't exist!";				
		} 
else 
	{				
$result[$key] = $record['values'][$_GET[$key]];		
}	
}

}	
if(empty($errors))
{	
$total = array_sum($result);	
echo "Your total is: $total!";
}
if(!empty($errors))
{	
echo "The following errors occurred-<br />";	
foreach($errors as $error)
{		
echo "$error<br />";	
}}
?>

 

beats me! ive copied the code from my post and tried it again however instead of gettin 21 I get 2! ?!?

 

I can only pressume that if we are having different values returned then my form must contain an error?

 

<html>
<head>
<title>Select a sword to craft</title> 
</head>
<body>
<form method="get" name "input" action="process3.php" >
<br />Tree Type<br />
<select name="treetype">
<option value="Alder">			Alder<option> 
<option value="Apple">			Apple<option>
<option value="Crab Apple">		Crab Apple<option>
<option value="Ash">			Ash<option>
<option value="Birch">			Birch <option>
<option value="Beech">			Beech<option>
<option value="Box">			Box<option>
<option value="Cherry">			Cherry<option>
<option value="Plum">			Plum <option>
<option value="Blackthorn">		Blackthorn<option>
<option value="Elm">			Elm <option>
<option value="Hawthorn">		Hawthorn <option>
<option value="Hornbeam">		Hornbeam  <option>
<option value="Holly">			Holly<option>
<option value="Juniper">		Juniper <option>
<option value="Lime">			Lime<option>
<option value="Maple">			Maple <option>
<option value="Oak">			Oak<option>
<option value="Pine">			Pine<option>
<option value="Scots Pine">		Scots Pine<option> 
<option value="Aspen"> 			Aspen<option>
<option value="Poplar">			Poplar <option>
<option value="Rowan">			Rowan<option>
<option value="Whitebeam">		Whitebeam<option>
<option value="Sorbus">			Sorbus<option>
<option value="Strawberry">		Strawberry<option> 
<option value="Willow">			Willow<option>
<option value="Yew">			Yew<option>
</select>
<br />Girth Size<br />
<select name="girthsize">
<option value="10to12"> 10 to 12</option>
<option value="12to14"> 12 to 14</option>
<option value="14to16"> 14 to 16</option>
</select>

<input type="submit" value=Submit />
</form>
</body>
</html>

LOL, when I tested, I didn't have a form, so I just set $_GET['treetype'] = '...'; variables in the code and I also removed the two unnecessary lines that are setting - $treetype = $_GET["treetype"]; and $girthsize = $_GET["girthsize"];

 

You have two problems -

 

1) The two lines of code that are setting $treetype = $_GET["treetype"]; and $girthsize = $_GET["girthsize"]; are also messing up the two arrays of data because they define the two variable names as scaler variables first, then they are treated as arrays. If you would use print_r($items), you could have seen where the problem is occurring at. You don't need these two lines and they weren't in the original code that I posted.

 

2) The code currently only matches exact values, so your value="..." attributes in the form must match the array keys exactly. Alder is not equal to alder.

In other words, this should work:

<?php
$_GET = array_map('strtolower',$_GET);
$treetype['alder'] = 10;
$treetype['apple'] = 14;

$girthsize['10to12'] = 11;
$girthsize['12to14'] = 13;

$items = array(); 
$items['treetype']  = array('legend'=>'treetype','values'=>$treetype);
$items['girthsize'] = array('legend'=>'girthsize','values'=>$girthsize);
$errors = array(); 
$result = array();
foreach($items as $key => $record)
{	
if(empty($_GET[$key]))
{				
$errors[] = "The {$record['legend']} type is empty!";
}
else  
	{				
if(!isset($record['values'][$_GET[$key]]))
		{					
$errors[] = "The {$record['legend']} type: {$_GET[$key]}, doesn't exist!";				
		} 
else 
	{				
$result[$key] = $record['values'][$_GET[$key]];		
}	
}

}	
if(empty($errors))
{	
$total = array_sum($result);	
echo "Your total is: $total!";
}
if(!empty($errors))
{	
echo "The following errors occurred-<br />";	
foreach($errors as $error)
{		
echo "$error<br />";	
}}
?>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.

×
×
  • 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.