Using random variables inside Arrays - php

First of all, sorry if this is worded poorly, as I'm a beginner at code.
I'm currently working on an online computer science course, however I'm quite confused on how to do one small part. We need to use arrays for this activity, where the user has multiple selections and each different selection has a different/unique text output. Everything works fine, except I need an option to choose a random selection, however I'm a bit confused on how to make it. You can see from my code the options 1-8. I want it to randomly select one of the selections.
Here's my code:
<?php
$train[0] = "Canada";
$train[1] = "Sahara Desert";
$train[2] = "Russia";
$train[3] = "Chernobyl";
$train[4] = "United States";
$train[5] = "North Korea";
$train[6] = "Germany";
$train[7] = "Hawaii";
?>
<!DOCTYPE html>
<html>
<head>
Took out everything here, it's not important.
</head>
<body>
<center>
<h1>Vacation Time!</h1>
<h4>You and your family just won the lottery! You all want to go on vacation, but nobody can agree where to go. Inside each train cart has a card with a location written on it. Whatever you find is where you're going! </h4>
<form name="form1" action="activity-2-7-arrays-a.php" method="post">
<label>Which cart on the train do you want to choose?</label>
<br>
<select name="cart" required>
<option value="1">First Cart</option>
<option value="2">Second Cart</option>
<option value="3">Third Cart</option>
<option value="4">Fourth Cart</option>
<option value="5">Fifth Cart</option>
<option value="6">Sixth Cart</option>
<option value="7">Seventh Cart</option>
<option value="8">Eight Cart</option>
<option value="show">Show all options</option>
<option value="any">Choose Randomly</option>
<br>
</select><br/>
<input type="submit" name="subButton" class="subButton" value="Go!"/><br/>
</form>
<h1><u>Final Results</u></h1>
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
$roll = rand(1,9);
if($cart == show) {
for($x = 1; $x <= 9; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
}
return;
}
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
return;
if ($cart == $roll) {
}
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll] . "! Have fun! </h2>";
?>
I'm sure it's a bit messy, also. Hopefully you understand what I mean. If you're able to explain the answer to me that would be extremely helpful. Thank you :)

You are randomly generating a value regardless of the user choice and comparing it with user's selection and other weird things.
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
$roll = rand(1,9);
You are generating a random value before even checking if user selected 'Choose randomly' and why generate a random between 1 and 9? Your $train array starts with index 0 and ends with index 7.
if($cart == show) {
String needs to be quoted.
for($x = 1; $x <= 9; $x++) {
Again looping $x from 1 to 9 makes no sense because of your array indexes.
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
Will fail when $x reaches 8 since last index in $train is 7.
}
return;
}
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
return;
So if user didn't select 'Show all options' you show him his chosen location. If user chose 'Select Randomly' this will fail since $cart would have value 'any' and $train['any'] does not exist.
Here is code with correct logic.
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
if ($cart == 'any') {// Check if user selected 'Choose Randomly'
$roll = rand(0, 7);
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll] . "! Have fun! </h2>";
}
else {
if ($cart == 'show') { // If user selected 'Show all options'
echo "<p> You could have ender up in... </p>";
for($x = 0; $x <= 7; $x++) {
echo "<h2> " . $train[$x] . "</h2>";
}
}
else { // User selected cart so show him chosen location
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
}
}
?>

Here is some problems in the code
from where and why we return?
no closing html-tags
I would change the last part of php-code like that:
<?php
if ($_POST['subButton']) {
$cart = $_POST['cart'];
$value = intval($cart);
$roll = mt_rand(1, 8); // mt_rand() has more entropy than rand()
if ($cart == 'show') {
// show target locations (according the OP-source)
for($x = 1; $x <= 8; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x-1] . "</h2>";
}
} else if ($value > 0 && $value <= 8) {
echo "<h2>"."Well, it looks like you're going to " . $train[$value-1] . "! Have fun! </h2>";
// idk why it needed, but move it here
if ($value == $roll) {
}
} else if ($cart == 'any') {
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll-1] . "! Have fun! </h2>";
} else {
// $_POST['cart'] has something wrong
}
}
?>
<!-- lines below was added to close html-tags -->
</body>
</html>

What you're looking for is array_rand():
$random = array_rand($train);

Instead of rand() use mt_rand() because the PHP DOCUMENTATION literally says
mt_rand — Generate a better random value
Regarding your php code, you have a lot of errors. This is how your bottom php code should look:
<?php
if($_POST['subButton'])
{
$cart = $_POST['cart'];
$roll = mt_rand(0,7);
//0-7 because those are the values you inserted into
//the $train[] array
if($cart == 'show') {
//another correction here, it has to be 0-7
for($x = 0; $x <= 7; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
}
}
else if ($cart!='any')
{
"<h2>Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
else //took out return and placed an else
{
echo "<h2>Well, it looks like you're going
to " . $train[$cart] . "! Have fun! </h2>";
}
?>

Related

php how to do a loop to calculate score for a quiz website

i am creating a quiz website using php where there are 4 questions for users to answer. there is a home page before this for them to choose either math or lit that they wish to do.
after selecting the subject, user need to answer the question and submit their answer, then the php code will calculate their score and count the number of correct/wrong answers.
<ArrayquesAns.php> is the array of questions and answers
it looks something like this, there are 2 array in this php, 1 is math question and another 1 is lit question
and here is the main code where it will generate questions from the question pool randomly. i also tried to put in the code to calculate score
<html>
<body>
<?php
require_once 'ArrayQuesAns.php'; //retrieve array of ques
$_SESSION["subject"] = $_GET['subject']; //suppose to put value when session starts
$_SESSION["name"] = $_GET['name'];
$subject = $_SESSION["subject"];
$name = $_SESSION["name"];
$url = "displayScore.php?name=" . $name . "&subject=" . $subject . "&";
if ($subject == "mathematics") { //math session
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
$MathquesRand = array(); //New array to contain the 4 random rows
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?> </h1>
<p>Hello <?= $name ?>! You may start your quiz !<p>
<hr>
<?php foreach ($MathquesRand as $qtsno => $value) { ?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
} else { //Lit Section
$LitQues_key = array_rand($Litques, 4);
$LitquesRand = array();
$i = 0;
foreach ($LitQues_key as $key) {
$LitquesRand[$i] = $Litques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?></h1>
<p>Hello <?= $name ?> ! You may start your quiz !<p>
<hr>
<?php foreach ($LitquesRand as $qtsno => $value) {
echo $value["ques"], " = \t";
?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
}
?>
<!--Exit-->
<button type="button">EXIT</button>
</body>
</html>
i think this part is where it has issue
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
the code should match user input answer with array question/answer to see if the answer is correct. every correct question will *5 and every wrong answer will *3 (the formula is in the code).
i am not sure if i place the code in the wrong bracket hence its not working or there is some logic error or should i run the code to find the score in a separate php?
after user submit their answer, it will redirect to another page that display their score and number of correct/wrong answers like this
score display html
Based on your original version of the MC test, please find below a working version:
To make it simple, I have removed the "Name" and "Subject" of the form to demonstrate the necessary coding.
You can still use the array_rand to draw 4 random questions
However, after the questions are displayed to the student (and student can input the answer) and clicked "Submit Attempt", the page will remember the random questions drawn - I have used a trick :- to store the questions randomly drawn into a hidden input box
The system will compare the student's submitted answer with that of the correct answer and determine whether it is correct or wrong, and show the score
To fix the "undefined array" errors you encountered, I applied the isset function on places relating to the $_GET variables. (Actually these are warnings, not errors, but it is for sure a good practice to use isset)
<?php
//require_once 'ArrayQuesAns.php'; //retrieve array of ques
$Mathques=array(
1=> array('no'=>1, 'ques'=>"3+1", 'ans'=>"4"),
2=> array('no'=>2, 'ques'=>"3+3", 'ans'=>"6"),
3=> array('no'=>3, 'ques'=>"3+4", 'ans'=>"7"),
4=> array('no'=>4, 'ques'=>"3+5", 'ans'=>"8"),
5=> array('no'=>5, 'ques'=>"3+6", 'ans'=>"9"),
6=> array('no'=>6, 'ques'=>"3+7", 'ans'=>"10"),
7=> array('no'=>7, 'ques'=>"3+8", 'ans'=>"11"),
8=> array('no'=>8, 'ques'=>"3+9", 'ans'=>"12"),
9=> array('no'=>9, 'ques'=>"3+10", 'ans'=>"13"),
10=> array('no'=>10, 'ques'=>"3+11", 'ans'=>"14")
);
if (! isset($_GET["draw"])) {
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
}
$MathquesRand = array(); //New array to contain the 4 random rows
if (! isset($_GET["draw"]) ) {
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
}
?>
<?php
if (isset($_GET["draw"]) && $_GET["draw"] !="") {
$pieces = explode(",", $_GET["draw"]);
$index=0;
while ($index < count($pieces)) {
if ($pieces[$index]!=""){
$MathquesRand[] = $Mathques[$pieces[$index]];
}
$index++;
}
}
?>
<form action="" method="get">
<?php
$correct=0;
$wrong=0;
?>
<h1> Section : Mathematics </h1>
<p>Hello ! You may start your quiz !<p>
<hr>
<?php
$pool="";
$ii=1;
foreach ($MathquesRand as $qtsno => $value) {
$pool.= $value["no"]. ",";
?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans<?php echo $ii; ?>"
<?php if (isset($_GET["userans".$ii]))
{
echo " value='" .$_GET["userans".$ii] . "'>" ;
} else { echo ">" ; }
?>
<?php if (isset($_GET["userans".$ii]) && $_GET["userans".$ii]==$value["ans"]) {
$correct++;
} else {
$wrong++;
}
?>
<br>
<?php
$ii++;
}
?>
<input name=draw type=hidden value="<?php echo $pool; ?>">
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
$score = ($correct * 5) - ($wrong * 3);
?>
<?php if (isset($_GET["draw"])) { ?>
<font color=red>Result:</font>
<br>Correct:<?php echo $correct;?>
<br>Wrong:<?php echo $wrong;?>
<br>Score:<?php echo $score;?>
<?php } ?>
To share my experience (I have coded such Multiple Choice Q & A functions many times) , in future if you want to do similar thing, please consider using
database to store the drawn questions ;
use ajax to compare the input data with the correct data stored in the db, instead of using form submission

PHP condition fails while using Session

I made a card game with PHP but there I'm facing some issue.
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
I'm getting an input from the user. The problem is, when the game loads at first, and the user enters an input and clicks submit, the game won't work. The condition ($_SESSION["bet"] != NULL) is giving true and bankroll is not defined.
Is there a way I can set this up properly? Is there some PHP method that can initialize the variable once then only works it on session start, then the rest of the code can take care of how that variable gets updated? The bankroll variable gets initialized if the user clicks submit without anything in it right now, so the game still works but it starts improperly.
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
The bankroll variable gets initialized to 1000 every time user submits a NULL input. I want to change this.
More code... Updating...
session_start();
$_SESSION["bet"] = $_POST["bet"];
echo "<br>";
//print_r($_SESSION);
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
else if ($_SESSION["bet"] > 1000 || $_SESSION["bet"] < 0)
{
echo " Please enter between 0 and 1000.";
}
else if ($_SESSION["bet"] > $_SESSION["bankroll"])
{
echo "You can't enter more than what you have.";
}
else
{
$deck = array();
for($x = 0; $x < 54; $x++) {
$deck[$x] = $x;
}
shuffle($deck);
//Then more stuff. This one for example...
if(($houseSuits[0] == -100) || ($houseSuits[1] == -100) || ($houseSuits[2] == -100) || ($houseSuits[3] == -100))
{
echo "<br>";
echo '<center> PLAYER WINS! (HOUSE HAS JOKER) </center>';
echo "<br>";
$_SESSION["bankroll"] = $_SESSION["bankroll"] + $_SESSION["bet"]; //THESE NEED TO BE ADDRESSED.
}
I JUST WANT TO FIND A WAY TO INITIALIZE BANKROLL TO 1000 AT START. THE WAY I'M DOING IT IS BY SUBMITTING A NULL VALUE THEN ASSUMING USER NEVER SUBMITS NULL VALUE AGAIN.
I WOULD LIKE BANKROLL TO BE INITIALIZED TO 1000, THEN FOR THE GAME TO TAKE CARE OF HOW BANKROLL GETS UPDATED.
I FOUND A WAY TO DO IT BUT IT'S NOT A PROPER WAY SO THAT'S WHY I'M ASKING FOR HELP.
THANK YOU.
Ok try this.
So if the bankroll is not set, then set it, once it's set it wont get set again because it's set.
Then any conditions after are fine.
session_start();
// Initialise bankroll if not already
if (!isset($_SESSION['bankroll'])) {
$_SESSION['bankroll'] = 1000;
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
}
$_SESSION['bet'] = $_POST['bet'];
if ($_SESSION['bet'] != NULL) {
echo "Your bet is: " . $_SESSION['bet'] . "<br>";
}
if ($_SESSION['bet'] > 1000 || $_SESSION['bet'] < 0) {
echo " Please enter between 0 and 1000.";
} elseif ($_SESSION['bet'] > $_SESSION['bankroll']) {
echo "You can't enter more than what you have.";
} else {
// Your card game stuff
}
Notes: you may have issues with using session as it'll store their bet wherever they are, so issuing a bet sets the session, then navigate elsewhere and come back and their bet will still be as before. Maybe this doesn't matter.
You also might not want to check if the bet is null, more perhaps empty or whatever. Test either way to be sure.

I have a simple php script for throwing dices, but all dices have the same number

I tried to make a dice script in php that should look like this one:
http://u11626.hageveld2.nl/po/opdracht1b/index.php
this is the link to mine:
http://u10511.hageveld2.nl/po/opdracht1b/index.php
Sorry if the answer is really obvious but i just can't figure out why the script doesn't work.
btw: "knop" means "button",and the pictures that I use as dices are called dobbelsteen1, dobbelsteen2 ..... dobbelsteen 6
<?php
session_start();
if (!isset($_SESSION["d1"]) || !isset($_SESSION["d2"]) || !isset($_SESSION["d3"])) {
$_SESSION["d1"]=0;
$_SESSION["d2"]=0;
$_SESSION["d3"]=0;
}
elseif (isset($POST["knop1"])) {
$_SESSION["d1"]=0;
}
elseif (isset($POST["knop2"])) {
$_SESSION["d2"]=0;
}
elseif (isset($POST["knop3"])) {
$_SESSION["d3"]=0;
}
elseif (isset($POST["knop4"])) {
$_SESSION["d1"]=0;
$_SESSION["d2"]=0;
$_SESSION["d3"]=0;
}
echo "d1 =" . $_SESSION["d1"];
echo "d2 =" . $_SESSION["d2"];
echo "d3 =" . $_SESSION["d3"];
if ($_SESSION["d1"]==0) {
$f = rand(1,6);
}
if ($_SESSION["d2"]==0) {
$g=rand(1,6);
}
if ($_SESSION["d3"]==0) {
$h=rand(1,6);
}
echo $f;
for ($r=1; $r<4; $r++) {
if (!$f==0) {
$f = 0;
echo "
<div align='center'>
<img src='dobbelsteen" . $f . ".gif'>
<form method='post'>
<input type='submit' name='knop1' value='Dobbelsteen gooien'>
</form>
";
}
elseif (!$g==0) {
$g = 0;
echo "
<div align='center'>
<img src='dobbelsteen" . $g . ".gif'>
<form method='post'>
<input type='submit' name='knop2' value='Dobbelsteen gooien'>
</form>
";
}
elseif (!$h==0) {
$h = 0;
echo "
<div align='center'>
<img src='dobbelsteen" . $h . ".gif'>
<form method='post'>
<input type='submit' name='knop3' value='Dobbelsteen gooien'>
</form>
";
}
}
?>
i have written what i consider an optimal script for this dice throwing exercise you are doing. I am giving you all the answers here but hopefully you will research my approach and learn from it.
<?php
//Start the php session
session_start();
//Initialise local dice array
//Check the session variable for already set values, if not set a random value
//Use TERNARY OPERATORS here to avoid multipl if else
$dice = array(
0 => (!empty($_SESSION['dice'][0])) ? $_SESSION['dice'][0] : rand(1, 6),
1 => (!empty($_SESSION['dice'][1])) ? $_SESSION['dice'][1] : rand(1, 6),
2 => (!empty($_SESSION['dice'][2])) ? $_SESSION['dice'][2] : rand(1, 6)
);
//If form has been submitted, and our expected post var is present, check the dice we want to role exists, then role it
//$_POST['roll_dice'] holds the index of the local dice value array element we need to update
if(!empty($_POST['roll_dice']) && !empty($dice[intval($_POST['roll_dice'])])){
$dice[intval($_POST['roll_dice'])] = rand(1, 6);
}
//Save the updated values to the session
$_SESSION['dice'] = $dice;
//Loop over the dice and output them
foreach($dice as $dice_index => $dice_val){
echo "<div class='dice' style='height:100px;width:100px;background-color:red;text-align:center;margin-bottom:50px;padding-top:10px;'>";
echo "<p style='style='margin-bottom:20px;'>".$dice_val."</p>";
echo "<form method='post'>";
echo "<input type='hidden' name='roll_dice' value='".$dice_index."' />";
echo "<input type='submit' value='Roll Dice' />";
echo "</form>";
echo "</div>";
}
?>
To add a new dice simply increase the size of the $dice array. For example the next one would be:
3 => (!empty($_SESSION['dice'][3])) ? $_SESSION['dice'][3] : rand(1, 6)
and then 4, and so on.
I hope this helps.
There are couple of issues with your script, as #Marc B has said "you never save the random numbers back into the session" also you are accessing the post data using $POST where as it should be $_POST, hope that can help you fixing your script.

Sticky forms in php

My code:
<label>Year: </label>
<?php
print '<select>';
$start_year = date('1910');
for ($y = $start_year; $y <= ($start_year + 104); $y++) {
print "<option value=\"$y\">$y</option>";
}
print '</select>';
?>
and our professor wants us to incorporate it being sticky with something like a code like this:
echo "<option value=\"$option\"";
if ($messageType == $option){
//make it sticky
echo ' selected="selected"';
}
echo ">$option</option>";
however that code isn't working with my code and i can't seem for it to become a default value/sticky.
In your for loop:
for ($y = $start_year; $y <= ($start_year + 104); $y++) {
($y== $option) ? echo '<option value="'.$y.'" selected="selected">'.$y.'</option>' : echo '<option value="'.$y.'">'.$y.'</option>';
}
I assumed that the value of $option is a year available in your for loop.
I hate to post an entire answer for this but i cannot comment yet... Given your problem "can't seem for it to become a default value" My money on its a very simple issue
echo ' selected="selected"';
should just be
echo ' selected';
http://www.w3schools.com/tags/att_option_selected.asp
but view source on the webpage it generates and make sure the HTML is generating as expected otherwise

multiple attribute form output

i have had made a number of changes to the below program but am really stumped on my last task- i need a multiple attribute to pull multiple 'teams' data (points,goal difference etc) with php form. i can get single teams to work but not multiple. see screen attached and heres my code below.
![enter image description here][1]
<html>
<head>
<style>
.red {color: red}
</style>
<title>Table</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" ){
$tablesPage = "http://www.bbc.com/sport/football/tables";
if(!empty($_POST["team"])){
$teamData= getTeamData($_POST["team"] , $tablesPage); //get associative array of team data
if(!empty($_POST["data"]) && $_POST["data"] == "results"){
echo getResults($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "position"){
echo getPosition($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "two points for a win"){
echo getPoints($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "goal difference"){
echo getDifference($teamData);
}
}
}
function getPosition($teamData){
/*This function takes an array of team data and returns a string containing the name of the team and its position in the leauge */
return "Team ". $teamData["team"] ." are currently number " . $teamData["position"] . " in the league " ;
}
function getResults($teamData){
/*This function takes an array of team data and returns a string containing the results of the team */
return $teamData["team"] ." have won " . $teamData["won"] . " , drawn " . $teamData["drew"] . " , and lost " . $teamData["lost"] . " games to date " ;
}
function getPoints($teamData){
/*This function takes an array of team data and returns a string containing the points and calculates the old two points system */
$oldpoints = $teamData["won"] * 2 + $teamData["drew"];
return $teamData["team"] ." have " . $teamData["points"] . " points under the current system " . "<br> Under two points for a win they would have " . $oldpoints ;
}
function getDifference($teamData){
/*This function takes an array of team data and returns a string containing the name of the team and its goal difference in the leauge */
return $teamData["team"] ." goal difference is " . $teamData["difference"] . " at the moment " ;
}
function getTeamData($team, $tablesPage){
/* This function takes a webpage url and the name of a team as two string arguments. e.g. getTeam(""http://www.bbc.com/sport/football/tables", "liverpool")
It returns an array of data about the team.
You don't need to understand what this function does just that it returns an array which contains keya and values. The values map to the following keys:
"position", "team", "played", "won", "drew", "lost", "for", "against", "difference", "points"
*/
$html = new DOMDocument();
#$html->loadHtmlFile($tablesPage); //use DOM
#$xpath = new DOMXPath($html); //use XPath
$items = $xpath->query('//td/a[text()="' . $team . '"]/../..'); //get the relevant table row
$values[] = array();
foreach($items as $node){
foreach($node->childNodes as $child) {
if($child->nodeType == 1) array_push($values, $child->nodeValue); //KLUDGE
}
}
$values[2] = substr($values[2], -1); //KLUDGE
$values = array_slice( $values, 2, count($values)-4); //KLUDGE
$keys = array("position", "team", "played", "won", "drew", "lost", "for", "against", "difference", "points");
return array_combine($keys, $values);
}
?>
<br>
Select a team and a data item about that team
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="team[]" multiple="multiple" size="3">
<option value=""></option>
<option value="Everton">Everton</option>
<option value="Arsenal">Arsenal</option>
<option value="Chelsea">Chelsea</option>
<option value="Man Utd">Man Utd</option>
<option value="Liverpool">Liverpool</option>
</select>
<select name="data">
<option value="position">position</option>
<option value="results">results</option>
<option value="two points for a win">two points for a win</option>
<option value="goal difference">goal difference</option>
<select>
<input type="submit" value="Get Data"></input>
</select>
</form>
</body>
</html>
Here is the code that you need to replace. I have left the 'debug' code in so you can see what is happening. just delete it when you are done.
Removed debug code.
Tested code: PHP 5.3.18 on windows xp.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" ){
$tablesPage = "http://www.bbc.com/sport/football/tables";
if(!empty($_POST["team"])){
// remember that the $_POST['team'] is an array of team names
foreach($_POST['team'] as $currentTeam) {
$teamData= getTeamData($currentTeam , $tablesPage); //get associative array of team data
if(!empty($_POST["data"]) && $_POST["data"] == "results"){
echo getResults($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "position"){
echo getPosition($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "two points for a win"){
echo getPoints($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "goal difference"){
echo getDifference($teamData);
}
echo '<br />';
} // end currentTeam
}
}

Categories