0

I have two variable definitions, and I am trying to understand the difference between the two so I can merge them into one.

PHP Definition 1:

$page = $_GET['page'];

PHP Definition 2:

$page = 0;
 if(isset($_GET['page'])){
    $page = (int) $_GET['page'];
 }

3 Answers 3

5

Your second definition will suppress any error encountered when $_GET['page'] isn't set by not trying to assign it to anything.

The (int) part in the second definition will cast $_GET['page'] to an integer value. This will inhibit any attacks you might get, although you should still be careful.

Finally, $page = 0 simply sets a default value for $page. If there is no value in $_GET, $page will remain with a value of 0. This also ensures that $page is always set, if you're using it in code below your snippet.

I don't know what you mean by merge them into one; the second snippet is an extension (and improvement) of the first.

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

5 Comments

So I should just be able to use the second one in place of the first, and it should work fine?
That is correct, providing the second piece of code gives you the functionality you want (only taking integers from $_GET['page']).
A shorter version can also include $page = (isset($_GET['page']) ? (int)$_GET['page] : 0);
Nice one @Brad, although ternary expressions can be confusing to some :-)
@Brad Christie yes, I get the idea of that expression, but I think for now I'm going to stick with the other notation... still learning here.
1

The first code block assigns to $page whatever value is in $_GET['page'].

The second one assigns a default value of 0 to $page. And the if statement will check first to see if $_GET['page'] is set (to avoid warnings). If it is set indeed, it will cast the value of $_GET['page'] to an integer and assigns it to $page.

3 Comments

so if the first one isn't defined as an integer, what is it defined as?
@stefmikhail: PHP isn't strongly typed, so (assuming a whole number is passed in) it will still be seen as an integer within php. The cast is "sanitizing" the input from the user, given it's in a URL (GET) variable and can be manipulated easily.
@stefmikhail: It will be whatever value $_GET['page'] contains. If it contains 123abc, that's what will be assigned to it. However, the second one will assign 123 to it. Read string conversion to numbers for full details.
0

I'd personally use:

$page = isset($_GET['page']) ? (int) $_GET['page'] : 0;

Or array_key_exists.

1 Comment

If OP doesn't understand the two code snippets in the question, how do you expect OP to understand your answer without an explanation?

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.