Value not saving into variable [closed] - php
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm making a hangman game.
Everything works somewhat fine untill one last part.
I want to show the letters he managed to guess correctly.
This works somewhat but only after the 2nd guess.
But that's not the main problem i'm struggling with.
When a user actually guesses a correct letter it shows it in the secret word.
(secret word meaning the word the user has to guess but in dash lines)
But when the user guesses another time, the previous letter dissapears out of the secret word.
The last thing i'm struggling on is that when there are multiple letters in the same word the loops stop at the first one it finds.
(excuse me for my bad scripting. I'm fairly new to this thanks!)
(also excuse my Dutch)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hangman Back end php</title>
<h1> Hangman </h1>
<h3>Raad een letter van het te raden woord</h3>
</head>
<body>
<?php
$hang[0] =
' -------
|/ |
|
|
|
|
|
/|\
-------------';
$hang[1] =
' -------
|/ |
| o
|
|
|
|
/|\
-------------';
$hang[2] =
' -------
|/ |
| o
| |
| |
|
|
/|\
-------------';
$hang[3] =
' -------
|/ |
| o
| |
| |
| /
|
/|\
-------------';
$hang[4] =
' -------
|/ |
| o
| |
| |
| / \
|
/|\
-------------';
$hang[5] =
' -------
|/ |
| o
| --|
| |
| / \
|
/|\
-------------';
$hang[6] =
' -------
|/ |
| o
| --|--
| |
| / \
|
/|\
-------------';
function HasBeenUsed($allLettersGuessed, $letter){
if ($allLettersGuessed =="") {
#No letter guessed yet
return false;
}
else {
$hasLetter = false;
#$length = strlen($allLettersGuessed);
$hasLetter = strpos($allLettersGuessed, $letter) !== false;
if ($hasLetter) {
$hasLetter = true;
return $hasLetter;
}
else {
$hasLetter = false;
return $hasLetter;
}
}
}
function Restart()
{
$wrongGuess = 0;
return array($oldLetterGuessed, $wrongGuess);
}
$solution = "DANSEN";
if (isset($_GET['letterGuessed'])) {
$currentGuess = $_GET['letterGuessed'];
# Check the letter
if (HasBeenUsed($solution, $currentGuess) == false) {
echo "<b> Wrong </b>";
$wrongGuess = $_GET['wrongGuess'] + 1;
echo "<pre>" . $hang[$wrongGuess] . "</pre>";
}
else {
$wrongGuess = $_GET['wrongGuess'];
echo "<pre>" . $hang[$wrongGuess] . "</pre>";
}
}
else {
$wrongGuess = 0;
$currentGuess = "";
}
echo "<form name = 'myForm' method='get' action='hangman.php'>";
# Alle geraden letters in een veriabele steken
if (isset($_GET['oldLetterGuessed'])) {
$oldLetterGuessed = $_GET ['oldLetterGuessed'];
$allLettersGuessed = $oldLetterGuessed . $currentGuess;
$allLettersGuessed;
echo "<input type = 'hidden' name = 'oldLetterGuessed' value ='". $allLettersGuessed ."'>";
echo $allLettersGuessed;
echo "<p> The number of wrong guesses so far is $wrongGuess </p>";
}
else {
echo "<input type = 'hidden' name = 'oldLetterGuessed' value = '' >";
}
echo "<input type = 'hidden' name = 'wrongGuess' value= '$wrongGuess'>";
if ($wrongGuess < 6) {
$alphas = range('A', 'Z');
# display letter buttons
for ($i=0; $i < count($alphas) ; $i++) {
echo "<input type = 'submit' name = 'letterGuessed' value = '" . $alphas[$i] . "' >";
}
}
else {
#The Screen when you're lost
echo nl2br("Oops looks like you've lost ");
echo nl2br("\n");
echo "The word you had to guess was ". $solution;
echo nl2br("\n");
echo "<form method = 'post' action = 'Restart()'>";
echo "<input type = 'submit' value = Restart'>";
echo "</form>";
}
echo "</form>";
#Display omzetten naar lijnen
$display = $solution;
$length = strlen($display);
for ($i=0; $i < $length ; $i++) {
$display[$i] = "-";
}
if (isset($oldLetterGuessed)) {
if ($oldLetterGuessed == "") {
$display = "_ _ _ _ _ _";
}
else
{
$currentGuess = $_GET['letterGuessed'];
# Looks at every letter and checks if it's the same
if (HasBeenUsed($solution, $currentGuess) == true ) {
# Positie zoeken $currentGuess in $solution
$posLetter = strpos($solution, $currentGuess);
# _ omzetten in de gegokte letter
if ($posLetter !== NULL) {
$display[$posLetter] = $currentGuess;
}
}
}
if ($display != $solution) {
echo $display;
}
else {
echo "You guessed the word";
}
}
?>
</body>
</html>
You can use sessions to store correct answers and their positions, here is an example based on your code:
Firstly start the session:
session_start();
Then you can store the correct guess and its position, this way:
$_SESSION['guessed'][$posLetter] = $currentGuess;
Above I create a session I called guessed to which I add the position and the current correct guessed letter.
Then when your page reloads it needs to display all correct guessed letters on their right position, so you need to loop on the session we created above :
if(isset($_SESSION['guessed'] )) { // Check if this session already exist
foreach ($_SESSION['guessed'] as $position=>$guessed ) {
$display[$position]=$guessed; // Assign the correct answer to the right position
}
}
Also, I recommend you to use post method in your form instead of get, and for this kind of games better you use JavaScript so it's faster and the page doesn't have to reload on each guessed letter.
Good luck!
every time you are guessing a number there is a server call, and the previous guessed letter no longer exists!
so, what you need to do is use $_SESSION :)
i will demonstrate it here:
in your PHP code:
<?php
session_start();
$_SESSION[word]=array();
// if a letter is correct just push it to your session array:
array_push($_SESSION[word],$letter);
// then you iterate the session array and according to the letters that resides there
// you revile the correct letters
Related
How can I convert multi text string to table
I have a string that contains multiple lines. how can I convert it into tables where in each td value is every word of each line. example of the string. Eth1/1 VPC_PEER_KEEPALIVE connected routed full 1000 1000base-T Eth1/2 VPC_PEER_KEEPALIVE connected routed full 1000 1000base-T expected table outcome: Eth1/1 | VPC_PEER_KEEPALIVE | connected | routed | full | 1000 | 1000base-T Eth1/2 | VPC_PEER_KEEPALIVE | connected | routed | full | 1000 | 1000base-T
<?php $str = "Eth1/1 VPC_PEER_KEEPALIVE connected routed full 1000 1000base-T Eth1/2 VPC_PEER_KEEPALIVE connected routed full 1000 1000base-T"; // echo $str; $v1 = explode(PHP_EOL, $str); foreach ($v1 as $key => $value) { $v2 = explode(" ", $value); echo "<tr>"; foreach ($v2 as $key2 => $value2) { echo "<td>" .$value2 ."</td>"; } echo "</tr>"; } ?>
This JS code will work- var string = "Eth1/1 VPC_PEER_KEEPALIVE connected routed full 1000 1000base-T"; //Whatever your string is string = string.split(" "); var table = "<table id='table' border='1px'><tr>"; for (i = 0; i < string.length; i++) { table += "<td>" + string[i] + "</td>"; } table += "</tr></table>"; document.write(table); //Whatever you want do with your table
how to add number into table array php saprfc [duplicate]
This question already has answers here: Zero-pad digits in string (5 answers) Closed 4 years ago. my table sap rfc how can I add number in front of ID? if ID contain 3 digits it will add 000 in front of ID, if ID contain 4 digits it will add 00 in front of ID, if ID contain 5 digits it will add 0 in front of ID. For an example ID | FEE | NAME | PERIOD 000711 | 204000 | YUDI MANDALA | 201807 000790 | 84000 | AGUS WAHYUDI | 201807 001171 | 151500 | SARJANA | 201807 my code: if ($FI_HPs!=0) { $array = []; for ($i=1;$i<=$FI_HPs;$i++) { $FI_HP = saprfc_table_read ($fce,"FI_HP",$i); $id = $FI_HP['ID']; if(isset($array[$id])) { $array[$id]['FEE'] += $FI_HP['FEE']; } else { $array[$id] = $FI_HP; } } foreach($array as $item) { echo '<tr> <td>'.$item['ID'].'</td> <td>'.($item['FEE']*100).'</td> <td>'.$item['NAME'].'</td> <td>'.$item['PERIOD'].'</td> </tr>'; } }
you could use str_pad foreach($array as $item) { echo '<tr> <td>'.str_pad($item['ID'], 6, "0", STR_PAD_LEFT) .'</td> <td>'.($item['FEE']*100).'</td> <td>'.$item['NAME'].'</td> <td>'.$item['PERIOD'].'</td> </tr>'; }
$base = 100000 ; '. substr($base+$item['ID'],1) .'
PHP crosstab formatting from array
Hi I have a PHP array like this $table=array(); $subject_names=array(); $subject_names[118]="English"; $subject_names[108]="Software Engeneering"; $table['Josh'][118]['int'] =55; $table['Josh'][118]['ext'] = 10; $table['Josh'][108]['int'] =45; $table['Josh'][108]['ext'] = 12; $table['Matt'][118]['int'] =45; $table['Matt'][118]['ext'] = 12; $table['Matt'][108]['int'] =50; $table['Matt'][108]['ext'] = 15; Here 118 and 108 are subject_id I am trying to format it like this student | English | Software Engeneering | | int. mark | ext. mark | int. mark | ext. mark | ___________________________________________________________ Josh | 55 | 10 | 45 | 12 Matt | 45 | 12 | 50 | 15 I tried echo "Student Name\t"; foreach($subject_names as $sub_name) { echo "$sub_name\t"; } echo "<br>"; foreach($table as $sname => $subjects){ echo "$sname\t"; foreach($subjects as $subject_name => $types) { foreach($types as $marks) { echo "$marks\t"; } } echo "<br>"; } It working fine but if I change the position of array item of table like $table['Josh'][118]['int'] =55; $table['Josh'][108]['int'] =45; $table['Josh'][118]['ext'] = 10; $table['Josh'][108]['ext'] = 12; It won't give a correct result. Is there anyway to assure that the result are always correct. Thank you for your any help and suggestions
Here's a solution I wrote for your request, picking the scores using the $subject_names as control rather than the students' scoresheet (I hope you get what I mean after going through the codes)... $table=array(); $subject_names=array(); // notice that I switched subject order, just to show that subjects control the marks displayed thereby ensuring consistent score mapping $subject_names[108]="Software Engeneering"; $subject_names[118]="English"; // and I'm using the rearranged scores (the sample use-case you specified in the question that distorts your output) $table['Josh'][118]['int'] =55; $table['Josh'][108]['int'] =45; $table['Josh'][118]['ext'] = 10; $table['Josh'][108]['ext'] = 12; $table['Matt'][118]['int'] =45; $table['Matt'][118]['ext'] = 12; $table['Matt'][108]['int'] =50; $table['Matt'][108]['ext'] = 15; echo "Student Name\t"; foreach($subject_names as $sub_name) { echo "$sub_name\t"; } echo "\n"; // proposed solution: foreach($table as $sname => $subjects){ echo "$sname\t"; foreach ($subject_names as $subject_id => $name) { foreach ($subjects[$subject_id] as $mark) { echo "$mark\t"; } } echo "\n"; } Here's the output of the script above... Student Name Software Engeneering English Josh 45 12 55 10 Matt 50 15 45 12 Running the same data through the script provided in the question, here's the output (distorted)... Student Name Software Engeneering English Josh 55 10 45 12 Matt 45 12 50 15 P.S: 'Engeneering' should be 'Engineering' I hope I've been helpful. Cheers!
codeigniter: how to transform/convert numbers data to text from the database?
for example, i have a table like this book | number data | ------------------------- book 1 | 2 | book 2 | 3 | book 3 | 1 | book 4 | 3 | every number has a name/value: Good for 1 Okay for 2 Bad for 3 how to transform the numbers and displays them in the form of text? without changing the original data
You can use an array to get status $output = Array(1=>"Good",2=>"Okay",3=>"Bad"); echo $output[$numberDate]; OR Use switch case like this: $output = "" switch ($numberDate) { case 1: $output = "Good"; break; case 2: $output = "Okay"; break; case 3: $output = "Bad"; break; } echo $output;
if ($number == 1) { echo "Good"; } elseif ($number == 2) { echo "Okay"; } else { echo "Bad"; } Don't use a switch statement, they tend to be slower.
Grouping similar records with php
I need help writing the logic of the php script which sorts data into a certain format... Firstly the script needs to loop through each s1 value and ping an endpoint to get the ml values (more like) which are actually referencing other s1 records. this is the easy part! the data is returned like so; Table 1 s1 | ml ---------- 1 | - 2 | 3,4 3 | 2,8,9 4 | - 5 | 2 6 | 1 7 | 10 8 | - 9 | - 10 | - Condition 1: As you can see the endpoint returns data for the s1 value telling it other s1 records are similar to other ones, but the direction of ml is not always bidirectional. sometimes, like when s1=6 the ml value is 1 however when s1=1 there isn't a ml value. Condition 2: Again just to explain the ml records, look above and below where s1=5 (above) and where s1=2 + rec=5 (below), this script needs to realise there is already an s1 record for it's value and that it should be added there. Condition 3: Note how when s1=2,ml=3 this is stored but when s1=3,ml=2 this is ignored because we have the reverse record. I basically want to match all the data into 1 sorted 'profile' so it ends up in the below format which i will store in another db table of 'sorted' records. Table 2 s1 | rec ---------- 2 | 3 2 | 4 2 | 8 2 | 9 2 | 9 2 | 5 6 | 1 7 | 10 This has been racking my brains for days now, I need something thats efficient because in the end it will deal with millions of records and I'm sure there is an easy solution but i just can't figure how to start it. I tried the following, but I'm stuck and don't know how to go further; public function getrelated($id='', $t=''){ if($id != ""){ $get = Easytest::where('s1','=',$id)->get(); if(count($get) > 0){ $ret= array(); foreach($get as $go){ $v = explode(",", $go->s2); foreach ($v as $e) { if($e != $t){ $ret[$e] = $this->getrelated($e, $id); } } } if(count($ret) > 0){ return $ret; }else{ return ""; } }else{ return $id; } }else{ return ""; } } public function easytest(){ ob_start(); $a = array( array("s1"=>1,"s2"=>implode(",",array()).""), array("s1"=>2,"s2"=>implode(",",array(3,4)).","), array("s1"=>3,"s2"=>implode(",",array(2,8,9)).","), array("s1"=>4,"s2"=>implode(",",array()).""), array("s1"=>5,"s2"=>implode(",",array(2)).","), array("s1"=>6,"s2"=>implode(",",array(1)).","), array("s1"=>7,"s2"=>implode(",",array(10)).","), array("s1"=>8,"s2"=>implode(",",array()).""), array("s1"=>9,"s2"=>implode(",",array()).""), array("s1"=>10,"s2"=>implode(",",array()).""), array("s1"=>11,"s2"=>implode(",",array(12)).","), array("s1"=>12,"s2"=>implode(",",array(2)).",") ); //return Easytest::insert($a); $records = Easytest::all(); foreach ($records as $record) { $id = $record->s1; echo "ROW: ".$id." > "; $record->s2 = ltrim($record->s2,","); $ml = explode(",",$record->s2); if(count($ml) >= 1){ foreach ($ml as $t) { echo "RESULT: ".$t." -".print_r($this->getrelated($t, $id), true); echo ",\n"; } } echo " <br><br>\n\n"; } return ob_get_clean(); }
Ok, so I eventually solved this... esentially this is the code below; improvements welcome :) You need to call the function like so related(array('searched'=>array(),'tosearch'=>array(13))); function: public function related($input){ $searched = $input['searched']; $ar = array(); $bits = array(); if(count($input['tosearch']) != 0){ $get = Easytest::orWhere(function($query) use ($input) { foreach ($input['tosearch'] as $k=>$v) { $query->orWhere('s2', 'LIKE', '%,'.$v.',%')->orWhere('s1', '=', $v); } }) ->orderBy('s1', 'ASC')->get(); foreach ($input['tosearch'] as $k=>$v) { unset($input['tosearch'][$k]); $input['searched'][$v] = $v; } foreach ($get as $result) { $thesebits = explode(",", trim($result->s2,",")); foreach ($thesebits as $smallbit) { if($smallbit != ""){ $bits[] = $smallbit; } } $bits[] = $result->s1; $bits = array_unique($bits); foreach ($bits as $k=>$v) { if(($key = array_search($v, $input['searched'])) == false) { $input['tosearch'][$v] = $v; }else{ unset($input['tosearch'][$v]); } } $input['tosearch'] = array_unique($input['tosearch']); } return $this->related($input); }else{ return $input; } }