Reputation: 21
I'm trying to make a program that accepts string even if it is misspelled as long as the first 2 letters is correct. Earlier when i run my program it works fine but when i put this
if(substr($player1, 0, 2) === "rock" || substr($player2, 0, 2) === "rock")
then click submit it will not print anymore. What did i do wrong with my code? or what function is supposed to be use?
<html>
<body>
<h1>ROCK PAPER SCISSORS</h1>
<?php
print ('<form action="" method="post">');
print ('<p>Player 1: <input type="text" name="p1" /></p>');
print ('<p>Player 2: <input type="text" name="p2" /></p>');
print ('<input type="submit" name="submit" value="PLAY" />');
print ('</form>');
if (isset($_POST['submit'])) {
$player1score = 0;
$player2score = 0;
$draw = 0;
$player1 = strtolower($_POST['p1']);
$player2 = strtolower($_POST['p2']);
if(substr($player1, 0, 2) === "rock" || substr($player2, 0, 2) === "rock"){
if ($player1 == 'scissors' && $player2 == 'scissors') {
$draw++;
print "Player 1: $player1score<br>";
print "Player 2: $player2score<br>";
print "DRAW: $draw";
}
else if ($player1 == 'rock' && $player2 == 'rock') {
$draw++;
print "Player 1: $player1score<br>";
print "Player 2: $player2score<br>";
print "DRAW: $draw";
}
else if ($player1 == 'paper' && $player2 == 'paper') {
$draw++;
print "Player 1: $player1score<br>";
print "Player 2: $player2score<br>";
print "DRAW: $draw";
}
else if ($player1 =='rock' && $player2 =='scissors') {
$player1score++;
print "Player 1: $player1score<br>";
print "Player 2: $player2score<br>";
print "DRAW: $draw";
}
else if ($player1 == 'rock' && $player2 =='paper') {
$player2score++;
print "Player 1: $player1score<br>";
print "Player 2: $player2score<br>";
print "DRAW: $draw";
}
else if($player1 == 'scissors' && $player2 == 'rock') {
$player2score++;
print "Player 1: $player1score<br>";
print "Player 2: $player2score<br>";
print "DRAW: $draw";
}
else if ($player1 =='scissors' && $player2 =='paper') {
$player1score++;
print "Player 1: $player1score<br>";
print "Player 2: $player2score<br>";
print "DRAW: $draw";
}
else if ($player1 =='paper' && $player2 =='rock') {
$player1score++;
print "Player 1: $player1score<br>";
print "Player 2: $player2score<br>";
print "DRAW: $draw";
}
else if ($player1 =='paper' && $player2 == 'scissors') {
$player2score++;
print "Player 1: $player1score<br>";
print "Player 2: $player2score<br>";
print "DRAW: $draw";
}
}
}
?>
</html>
</body>
Upvotes: 2
Views: 200
Reputation: 1359
The problem is in the string 'rock'
, because the substr
will only return 2 characters, not 4.
Here is what you should do:
// Checking for "rock", but only care about the beginning of "ro" ck
if(substr($player1, 0, 2) === "ro" || substr($player2, 0, 2) === "ro")
I hope that helps.
Upvotes: 1