1

I am having problems creating a simple PHP script. The $_GET["give"] variable is always 0 in PHP, but I did define it in the URL. If it's not defined, my script redirects.

    if (isset($_GET["give"])&&$_GET["give"]!="") {
        echo "give GET detected<br />";
        $user = $_GET["give"];
        echo $_GET["give"]+$user+"<br />";
    }
    header("Location: /diamonds/"); //this document, but removing arguments.

The URL is fine, /?give=kroltan, it should echo kroltan. But instead, I get this in the browser:

   give GET detected <br>
   0

It doesn't even echo the $user variable, although it's the same value as $_GET["give"]. And no <br> after that too

4 Answers 4

6

This is PHP. You concat strings with a . and not a +.

As @MarcB said in the comments - in other words, you're doing a mathematical addition on strings, so PHP is converting your kroltan string to a 0.

String operators in PHP

Sign up to request clarification or add additional context in comments.

2 Comments

in other words, you're doing a mathematical addition on strings, so PHP is converting your kroltan string to a 0.
I love your addition @MarcB; I'll add it in the answer
1

By using a plus sign PHP thinks it is dealing with numbers and thus changes the string into a number. Which results in an integer with the value zero. Therefor you will always get the value zero back. Due to the values of the strings being zero.

If you want to combine strings you should use the dot instead of a plus sign.

So instead of:

echo $_GET["give"]+$user+"<br />";

You should use

echo $_GET["give"] . $user . "<br />";

Btw the code will always redirect, because you are not using an else statement, also why are you assigning the value of $_GET['give'] to $user and combining them in the next line? That seems odd.

1 Comment

This is a partial code, focused in the issue. In the full code the redirect is inside this if, but outside my important code (which retrieves things from a MySQL database (yes I am escaping it). Having bot the $_GET["give"] and $user was a test, I am actually using only $user, so I can put it inside strings without separating them (like "hello $user, how are you").
0

In PHP, the + operator is for algebraic addition, whereas . is used for string concatenation.

Comments

0

You are using numeric addition (+) operator instead of string concatenation (.) one in $_GET["give"]+$user+"<br />". PHP happily converts non-numeric strings to zeroes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.