-3

I have lots of PHP statements along the lines of:

$getvalue = $_GET['valueiwant'];

In some scenarios not all variables are available. So, let's say 'valueiwant' doesn't exist in the URL string, how can I return a value based on the fact it doesn't exist?

For example if 'valueiwant' can't be found set $getvalue to -1

Currently it appears the value defaults to 0 and I need to be equal less than 0 if it doesn't exist.

Any ideas?

thanks

Dan
  • 2,304
  • 6
  • 42
  • 69

2 Answers2

5

I always use

$getvalue=isset($_GET['valueiwant'])?$_GET['valueiwant']:-1;
Voitcus
  • 4,463
  • 4
  • 24
  • 40
  • Perfect, although I prefer `array_key_exists()` instead of `isset()` because isset will return `false` if the value is null – Michel Feldheim Mar 04 '13 at 21:02
  • 2
    @MichelFeldheim `$_GET` data will never contain a null value unless you intentionally inject it. – Wesley Murch Mar 04 '13 at 21:03
  • Perfect, thank you. Will accept the answer in 5 minutes when I'm allowed! – Dan Mar 04 '13 at 21:07
  • 1
    @MichelFeldheim: I think $_GET are always of `string` type, even if it is a number. If you want `NULL` you'll get an empty string (length 0). – Voitcus Mar 04 '13 at 21:07
0

Use of the isset() function checks if the offset exists, and returns a boolean value indicating it's existence.

This means that you can structure an if statement around the output.

christopher
  • 26,815
  • 5
  • 55
  • 89