Having Trouble with PHP Word Guessing Game - php

<?php
if(isset($_POST['submit'])) {
$guess = $_POST['guess'];
$count = isset($_POST['count']) ? $_POST['count']:0;
$count++;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Guess the Word Game</title>
</head>
<body>
<div id = "header">
</div>
<div id = "word">
<?php
//create array
$words = array("aardvarks", "determine", "different", "greatness", "miserable");
$random = array_rand($words);
//choose a random word from array
$newWord = $words[$random];
$change = str_split($newWord);
//prints out array
/*foreach($change as $list) {
echo $list;
}*/
$masked = str_replace($change, '*', $change);
//prints masked array
foreach($masked as $hide) {
echo $hide;
}
?>
</div>
<div id = "guess">
<form name="guessLetter" method="POST" action=""
<p>Please input your guess below</p>
<input type="text" name="guess" id="guess"/><br />
<input type="hidden" name="count" id="count" value="<?php echo $count; ?>" />
<?php
?>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit'])) {
echo "Guess: ".$guess."<br />";
echo "Count: ".$count;
}
?>
</div>
</body>
</html>
Hi everyone
I am relatively new to PHP and in the process of creating a word guessing game.
I have created an array of words and then randomized them. Once a word has been chosen, I have split the word into an array. I have then created another array for the masked version of the word which appears on the screen.
I have been ok up to here, but I now need to use a loop to iterate through array to see if the letter guessed is actually in the word. I also want to tell the user how many times the letter appears and also update the masked version of the word, with the actual letter.
I have included my code so far and would really appreciate some help as I am stuck!!

I now need to use a loop to iterate through array to see if the letter guessed is actually in the word
$letter_is_in_word = stristr($selected_word, $guess);
// returns either false if not found, or a section of the string
// where it was found ($letter_is_in_word == true)
I also want to tell the user how many times the letter appears
$number_of_occurences = substr_count($selected_word, $guess);
... and also update the masked version of the word, with the actual letter.
// get your random word
$random = array_rand($words);
$selected_word = $words[$random];
// set up temporary array to store output letters or *
$output = array();
// split word into each letter
$letters = str_split($selected_word);
foreach($letters as $letter) {
// if the letter was guessed correctly, add it to the output array,
// otherwise add a *
$output[] = ($letter == $guess) ? $letter : '*';
}
// output the results (implode joins array values together)
echo implode($output);
Something to note here is that while you are tracking the guess count via hidden input field, you aren't tracking previous guesses. I would suggest you use a hidden input field to store previous guesses also.
At the top of your page:
$count = 0;
$guesses = array();
if(isset($_POST['guesses']))
$guesses = explode('|', $_POST['guesses']);
if(isset($_POST['submit'])) {
$guess = trim(strtolower($_POST['guess']));
if(!in_array($guess, $guesses))
$guesses[] = $guess;
$count = isset($_POST['count']) ? (int) $_POST['count'] : 0;
$count++;
}
Then further down:
<input type="hidden" name="guesses" id="guesses" value="<?=implode('|', $guesses)?>">
This allows you to track previous guesses (hidden field in this example is delimited by | characters). You'll then need to check that array when you decide which letters to * out:
foreach($letters as $letter) {
// if the current letter has already been guessed, add it to
// the output array, otherwise add a *
$output[] = in_array($letter, $guesses) ? $letter : '*';
}

Related

Echoing part of a PHP string back within conditional value of HTML form field

I am building an HTML form - a simplified, two field version of which is below. The user is meant to enter something like the below string into the first field of the form:
https://www.facebook.com/dialog/feed?app_id=12345&link=http%3A%2F
%2Fbit.ly%2F12345&picture=https://website.com/horse-picture.jpg&name=Headline&
description=Description&redirect_uri=http%3A%2F%2Fwww.facebook.com%2F&
caption=Something
I am trying to split this string so that only the following part of the string is echoed into the second field of the form:
horse-picture.jpg
If the first field is empty, the second field is echoing back its own value. I've marked where the trouble is below. I've seen several threads on using explode, but the part of the string I'm looking to echo back isn't flanked with the same consistent characters, and the length of this string will vary, so preg_match also seems to be not a good option. Having this nested within a conditional is also throwing me off. Would very much appreciate help. Thanks!
<h2>THIS IS AN HTML FORM</h2>
<form action="sharefile.php" method="post">
<label for="decode">FB decode:<br /></label>
<input type="text" id="decoder" name="decoder" size="70" value="" /><br /><br />
<label for="img">Image (e.g. horse-picture.jpg):<br /></label>
<input type="text" id="img" name="img" size="70" value="
<?php if (strlen($_POST['decoder']) > 0)
//THIS IS WHERE THE TROUBLE STARTS
{SOMETHING GOES HERE}
//THIS IS WHERE THE TROUBLE ENDS
else {echo $_POST['img'];}
?>"
<input type="submit" value="Submit!" name="submit" />
</form>
Something like this might work. I believe you want to parse the picture URL, yes?
<?php
function scrub($string) {
// Parse the picture variable.
$matches = array();
$result = preg_match("/picture=([^\&]+)/", $string, $matches);
$url = $matches[1];
// Scrub the picture URL.
$result = preg_replace('/https?:\/\/[^\/]+\//', '', $url);
print_r($matches);
print_r($result);
}
scrub("https://www.facebook.com/dialog/feed?app_id=12345&link=http%3A%2F%2Fbit.ly%2F12345&picture=https://website.com/horse-picture.jpg&name=Headline&description=Description&redirect_uri=http%3A%2F%2Fwww.facebook.com%2F&caption=Something");
/*
Result:
Array
(
[0] => picture=https://website.com/horse-picture.jpg
[1] => https://website.com/horse-picture.jpg
)
horse-picture.jpg
*/
It looks like you're trying to parse URLs. PHP has functions for that, of course, albeit slightly weird functions, but it's PHP, so we expect that:
$url = '.. your massive URL inception ..';
$_url = parse_url($url);
print_r($_url);
parse_str($_url['query'], $query);
print_r($query);
$_url = parse_url($query['picture']);
print_r($_url);
$picture = basename($_url['path']);
var_dump($picture);
Example: http://3v4l.org/GKKmq#v430
Another method. Since this is a URL, first split on the question mark ? and take the second element, the query string. Now split on the ampersands & and loop through them looking for the key/value pair starting with "picture=". Once that is found grab the portion of the element after that many characters (8 characters in "picture="), then split the string on the forward slash / and grab the last element in that resulting array.
If $_POST['decoder'] equals:
https://www.facebook.com/dialog/feedapp_id=12345&link=http%3A%2F%2Fbit.ly%2F12345&picture=https://website.com/horse-picture.jpg&name=Headline&description=Description&redirect_uri=http%3A%2F%2Fwww.facebook.com%2F&caption=Something
Then:
list($d, $q) = explode('?', $_POST['decoder']);
$pairs = explode('&', $q);
foreach ( $pairs as $value ) {
if ( !(strpos($value, 'picture=') === FALSE) ) {
$picture = explode('/', substr($value, 8));
$picture = $picture[count($picture) - 1];
break;
}
}
echo $picture;
Outputs:
horse-picture.jpg
You should do something like this:
<?php echo '<input type="text" id="img" name="img" size="70" value="'.$whatyouwant.'"'; ?>
Hope it helps!

PHP: Function() check form indexed array

EDIT:
I solved my problem:
Thanks to all of you for your comment, it help me to think differently:
I didn't know that return ...; was behaving this way ( I believed it was just sending value not ending function ), so like I said, I'm just starting, I' a newbie...
I solved my problem with multidimensional array, I think it should work like I want now. I posted the code at the end of this post.
------------------------------------------------------------
I'm trying to make a basic checking form function that would be used to check all the form on my future website.It took me several hours (days...) to do this short code, because I'm a newbie in PHP, i just began few days ago.
Here is the Idea (Note that the form is way bigger I just created a smaller version of it for debugging).
PHP Library included with require() in the HTML page:
function check_form() {
$n = 0;
$indexed = array_values($_POST);
// How should I do to make this loop,
// to edit the HTML of each input one by one,
// without modifying other input that the one corresponding
// to the $n position in the table ?
if (isset($indexed[$n])) {
if (!empty($indexed[$n])) {
$value = $indexed[$n];
$icon = define_article_style()[0];
$color = define_article_style()[1];
} else {
$value = define_article_style()[4];
$icon = define_article_style()[2];
$color = define_article_style()[3];
}
$form_data_input = array($value, $icon, $color);
return $form_data_input;
}
}
The HTML Form:
<form role="form" method="post" action="#checked">
<div class="form-group <?php echo check_form()[1]; ?>">
<label class="sr-only" for="title">Title</label>
<input type="text" name="title" class="form-control input-lg" id="title" placeholder="Enter title * (min: 5 characters, max: 30 characters)" value="<?php echo check_form()[0]; ?>">
<?php echo check_form()[2]; ?>
</div>
<div class="form-group <?php echo check_form()[1]; ?>">
<label class="sr-only" for="another">Title</label>
<input type="text" name="another" class="form-control input-lg" id="another" placeholder="Enter title * (min: 5 characters, max: 30 characters)" value="<?php echo check_form()[0]; ?>">
<?php echo check_form()[2]; ?>
</div>
<button type="submit" class="btn btn-default" name="check_article" value="#checked">Check</button>
</form>
My problem is that the values returned to the inputs is always the content of "title", so for example if
$array[0] = $indexed[$index];
$array[1] = define_article_style()[0];
$array[2] = define_article_style()[1];
for "title" is equal to
$array[0] = "blabla";
$array[1] = "myclass1";
$array[2] = "myclass2";
every other input (in this case it's just "another") of the form have the same values.
I'm a bit confused, and I don't understand very well how everything works but I think this is related to the fact that the inputs share $array[n]to get their values/style but I don't really understand how I can keep this concept and make it work.
So if you understand what isn't working here I would be interested about explanation (keep in mind, I'm a newbie in code, and PHP.)
Thank you.
Greetings.
------------------------------------------------------------
Here is my working code ( I have to verify but I think it works correctly ).
function check_form() {
$n = 0;
$index_post = array_values($_POST);
while ($n < count($index_post)) {
if (isset($index_post[$n])) {
if (!empty($index_post[$n])) {
$value[$n] = $index_post[$n];
$color[$n] = define_article_style()[0];
$icon[$n] = define_article_style()[1];
} else {
$value[$n] = define_article_style()[4];
$color[$n] = define_article_style()[2];
$icon[$n] = define_article_style()[3];
}
}
$array_all = [$value, $color, $icon];
$n = $n + 1;
}
return $array_all;
}
Again, thanks for the answer, good to see that even newbies that don't understand half of what they do when they use this function over this other function get answers here.
Thumps up.
Greetings.
You have a lot of errors in your code:
First: I supose you have a view file "form.php" and the process for the submit form in "submit_form.php", so in your html code you need to fix this (action attribute):
<form role="form" method="post" action="submit_form.php">
Second: You have 2 input tags with names "title" and "another", so the $_POST array have 2 indexes:
$_POST["title"], $_POST["another"], you can check the content of this array:
var_dump($_POST); // this function print all the data of this array, check it.

PHP - odd one out

I am trying to create a "find the odd word" application (given a list of words like cat, dog, bird and car, the latter is the odd one because it's not an animal).
Firstly, I retrieve and shuffle randomly five words from the DB. They are called: odd (which is the odd one), one, two, three, four (which are the other four).
Then, I produce a form (radio button) with the five words, so that users can select one of their choice:
$words = array
(
$odd,
$one,
$two,
$three,
$four,
);
shuffle($words);
foreach ($words as $word)
{
$string = $word;
echo '<html><input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br></html>';
}
In the next PHP page, I want to check if the selected word is the odd one. I can't figure out how to do it.
Any suggestions? Thanks!
Use the $_SESSION variable to handle this to find out if the odd was selected or not
Say the following code is from your Odd.php that displays the radio buttons (assuming you would handle the form element and submit button)
<?php
session_start();
$_SESSION['odd'] = $odd;
$words = array
(
$odd,
$one,
$two,
$three,
$four,
);
shuffle($words);
echo '<form method="POST" action="Next.php">';
foreach ($words as $word)
{
$string = $word;
echo '<input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br>';
}
echo '<input type="submit" /></form>';
?>
On your Next.php file use the code below to validate if the odd was selected or not
<?php
session_start();
$odd = $_SESSION['odd'];
if ($_REQUEST['odd'] == $odd) { // $_REQUEST handles both $_POST and $_GET
echo "Odd was selected";
} else {
echo "Odd was not selected";
}
?>
Hope this helps!
You need to carry the odd word to the next page somehow. There are many different ways of doing this, arguably the easiest one is by saving the odd word in a variable in your form
<input type="hidden" name="realodd" value="<?php print $odd; ?>" />
On the next page, you can then check whether the chosen word is right by comparing it to the hidden word.
if ($_POST['realodd'] == $_POST['odd']) {
print "You found the odd word.";
}
This could easily be broken by just looking at the source code. A better solution could be saving the odd word in a session cookie:
session_start();
$_SESSION['realodd'] = $odd;
And then verify on the next page almost like before
if ($_SESSION['realodd'] == $_POST['odd']) {
print "You found the odd word.";
}
session_start();
if(isset($_POST['odd'])&& isset($_SESSION['odd'])&& $_POST['odd']==$_SESSION['odd']){
exit ("You're a genius, you got the right word");
}else{
if (isset($_POST['odd'])){ echo "Sorry, try again";}
}
//sql query goes here
$words = array
(
$odd,
$one,
$two,
$three,
$four,
);
$_SESSION['odd'] = $odd;
shuffle($words);
echo '<form method="POST">';
foreach ($words as $word)
{
echo '<input type="radio" name="odd" value="$word"/>$word<br><br>';
}
echo '<input type="submit" value="Submit"/>';
echo '</form>';

removing last element from a multidimensional array in php

I have a textbox that iterates 5 times and displays values from the textbox into an array.
<form method="post" action="test.php">
<?php for($i = 0; $i < 5; $i++) {
echo "<input type='text' name='text1[]'/>";
} ?>
<input type="submit" name="confirm" value="confirm" />
</form>
<?php
$text1 = $_POST['text1'];
$count= count($text1);
if(isset($_POST['confirm'])) {
for($p = 0; $p < $count; $p++) {
echo print_r($p[$i]);
}
}
?>
I want to remove the last value (which is that repeating number 1) from the data and only display the names. The output of above is as follows:-
John1
Jack1
Peter1
Jane1
Jill1
echo print_r($p[$i]);
print_r prints content of $p[$i] and returns 1 that is passed to echo (and printed next to desired output). You don't need print_r here.
print_r sends $p[$i] to the output buffer and then it returns a boolean result, which will be true (or 1 when echoed out).
So, the solution is simply to not use print_r.
Always read the documentation when you are unsure about something. Pretty much anything you want to know about PHP can be found there.

Read from an HTML textarea and then insert the data into a PHP array

I've been trying to create a tracker and everything is going smoothly thus far, just one new feature I'm trying to work on has me stumped. I'm trying to have it so the person who starts a tracker can enter names and the tracker will grab the names the user entered and look them up.
The only way that I can think of accomplishing this would be to insert the names from $_POST['names'] and insert them into an array, but when I do this, it only creates one index inside the array.
This is the code that I'm using:
$lol = array();
$l = array($_POST['names']);
foreach ($l as $textarea) {
array_push($lol, nl2br($textarea));
}
for ($a = 0; $a < count($lol); $a++) {
echo "index " . $a . ": " . $lol[$a];
}
The result of that is:
index 0: lol
not
sure
how
this
will
work
I typed the above out in the text field with spaces. Here's the HTML file that I'm using as well:
<body>
<form name="form" action="test.php" method="GET">
<div align="center">
<textarea cols="13" rows="10" name="names"></textarea><br>
<input type="submit" value="lol">
</div>
</form>
</body>
So I guess what I'm asking is, is it possible to have a person put, say, "Ron", "Mark", "Tommi", and "Daniel" in the text box, could I insert "Ron", "Mark", "Tommi" and "Daniel" into an array so that their index would be [0, 1, 2, 3] respectively, and if so how would I achieve this?
Use explode to split a string by another substring.
$lines = explode("\n", $_POST['names']);
print_r($lines);

Categories