php - Associative array from form inputs -
i'm building calculator mmo guild. @ moment i'm looking way make data more easy access calcules.
basically, have form 5 text fields (just test, there lot more), , select list (for choose proper equation).
example code:
<input type="text" id="strength" name="strength" value="0"> <input type="text" id="dexterity" name="dexterity" value="0"> <select name="equation" id="equation"> <option name="damage" id="damage">damage</option> <option name="defense" id="defense">defense</option> </select>
so form procesed through php file.
<form action="file.php" method="post"> //inputs here <input type="submit" value="calculate"> </form>
at moment i'm receiving data in php file vars:
$strength = (int)$_post['strength']; $dexterity = (int)$_post['dexterity'];
for start ok, when script complete there more 20 fields... wanna store data in array, this:
$strength = array( 'fuerza' => 125, 'dexterity ' => 125, //and more fields... );
and use data in various different functions equations:
function equation1() { $damage = $stats['dexterity'] + $stats['strength']; }
i have read several posts , tutorials use name value inputs create array somethin this: name="name[]". doesn't work me how want. calculator receive 1 value each "stat", , need have these values in array can access them different fuctions in script.
please ask me if question not clear, , sorry if english bad.
edit after solve
i let here code after solve:
.html example:
<input type="text" id="strength" name="stats[strength]" value="0"> <input type="text" id="dexterity" name="stats[dexterity]" value="0"> <select name="operation" id="operation"> <option name="damage" id="damage">damage</option> <option name="defense" id="defense">defense</option> </select>
.php example:
function critop($stat) { $result = $stat * 0.00725; return $result; } switch($_post['operation']){ case 'damage' : $critical = critop($_post["stats"]["dexterity"]); break; //more case...
you can use brackets in name field direct php stick them in array. if use []
form numerical array, can specify associative key in brackets [dexterity]
<input type="text" id="dexterity" name="strength[dexterity]" value="125"> <input type="text" id="fuerza" name="strength[fuerza]" value="125">
this result in
$_post['strength'] = array( 'dexterity' => 125, 'fuerza ' => 125, );
bonus points
you can continue enforce integer values using array_map:
$_post['strength'] = array_map('intval', $_post['strength']);
this make sure values integers.