Explaination of a line of code

Can someone please explain what the following line of code is doing.

[php] $id = isset($_GET[‘id’]) ? $_GET[‘id’] : 0;[/php]

I have looked up isset and understand that okay but $_GET and the “?” to the next $_GET and the final “: 0;” I do not understand.

Any help appreciated.

Hi freddo99,

What you are seeing is a shorthand formatted if statement.

What this is doing is:

Checking to see if the url for the page contains either ?id=something or &id=something. If it does it assigns the id value (something) to the variable $id. If it doesn’t, it assigns 0 to $id.

$_GET is a way of passing values to a webpage by including them in the url. To see this in action, create a php file named “test.php” and copy the following into it:[php]

Get Demo <?php if(isset($_GET['word'])) echo "Your word was ",$_GET['word']; else echo "You didn't enter a word."; ?> [/php]

Now go to the page you just created (in your browser) and you should see “You didn’t enter a word.” Go up to your url bar and add “?word=fandango” to the end of the url. You should now have something similar to: http://www.mywebsite.com/test.php?word=fandango". Hit enter and your page should now say: Your word was fandango

If you wanted to pass an additional value, you would just add an ampersand (&) and the next value. This would look like this: http://www.mywebsite.com/test.php?word=fandango&name=freddo99

As to the shorthand format for a php if statement, it is for setting the value of a variable based on a logic test. You start with the variable you wish to set, followed by an equal sign and your test: isset($_GET[id’]) followed by a question mark (?) and what to set the variable to if the test is true, followed by a colon (else) and finally what to set the variable to if the test is false.

It is important to test if $_GET[‘id’] is set before attempting to use it or php will throw a warning if it isn’t (depending on your error reporting settings. Some people also use !empty() (not empty) in place of isset(). The two are slightly different; and, while they can often be used interchangeably, there is a definite place for each.

Please let me know if this isn’t clear. I probably didn’t word it very well…

jay

Many thanks malasho

Your explanation and example were just what I needed. I now follow what is happening with the code. I’m still trying to come to grips with regular PHP let alone shorthand!

I appreciate you tkaing the time to help

Freddo99

My pleasure. I’m not a fan of this format myself, but to each there own!

Best,

jay

Sponsor our Newsletter | Privacy Policy | Terms of Service