Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string matching via if statement PHP

I have an input text area which when filled out and sent, puts whatever was typed in into the variable

$input

This is then put through an if statement to check whether or not its the letter a. If it is then echo - you wrote the letter a, else - you did not write the letter a.

<?php    
 $input = $_POST["textarea"];

    echo $input;
    echo "<br />";

    if($input = "a"){
    echo "You wrote a";
    }else{
    echo "You did not write a";
    }


    ?>

It does work, but in the wrong way. Every letter I type in comes as 'You wrote a'. I only want it to echo this if the user typed a. Otherwise, echo 'You did not write a' .

EDIT: When I try == instead of = it says 'You did not write a' for everything. Even when I type a.

EDIT 2: When I try the string compare parameter, It didnt work. Any suggestions where I am going wrong?

FULL SCRIPTS OF BOTH PAGES:

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

</head>

<body>
<h1>Fun Translator</h1>

<form method="post" action="query.php">
 <textarea name="textarea" id="textarea">
 </textarea>
 <input type="submit" name="send" value="Translate" />
</form>


</body>
</html>

query.php

<?php
$input = $_POST["textarea"];

echo $input;
echo "<br />";

if(strcmp($input,'a')==0){
    echo "You wrote a";
    }else{
    echo "You did not write a";
    }


?>

Solution:

trim()

like image 849
RSM Avatar asked Nov 30 '22 17:11

RSM


1 Answers

== is the conditional for comparison. = is the assignment operator.

if($input == "a"){
    echo "You wrote a";
    }else{
    echo "You did not write a";
    }

You might want to use strcmp as it is binary-safe.

if(strcmp($input,'a')==0){
    echo "You wrote a";
    }else{
    echo "You did not write a";
    }

http://php.net/manual/en/language.operators.comparison.php

http://php.net/manual/en/function.strcmp.php

EDIT: Taking another stab here - in your code as posted (I copy pasted it) you have whitespace in your textarea by default.

Don't put a line break between the and tags. This adds whitespace to the start of 'a'.

Removing this made it work properly in my test.

EDIT: As per the accepted answer and reposted code, trim() is in fact the proper function to remove all leading and trailing whitespace.

like image 169
DeaconDesperado Avatar answered Dec 10 '22 07:12

DeaconDesperado