-2

Possible Duplicate:
Where can I read about conditionals done with ? and :

I want do the following without using if else or a ternary operator:

if $_GET['a'] is not null then set $a= $_GET['a'] else set its value to "default".

I tried $a= $_GET['a'] || "default". but it doesnt work. I remember seeing something like this in a code sample, but I can't recall now.

Community
  • 1
  • 1
hoshiKuzu
  • 715
  • 1
  • 9
  • 25
  • 1
    A simple Google search will give u http://php.net/manual/en/function.is-null.php – Prashant Singh Oct 22 '12 at 07:09
  • He said he didn't want a ternary operator – Delta Oct 22 '12 at 07:12
  • Then just use an *if* or actually understand the operators. They are documented. `(NULL !== $a = $_GET['a']) || $a = "default";`. This is trivial material. – hakre Oct 22 '12 at 07:14
  • 1
    Although I am not too sure I understand what the OP is trying to achieve, I'm pretty sure he DIDN'T ask "how to determine if a variable contains null" and cleraly stated that he DIDN't want to use the ternary operator... – Pierre Henry Oct 22 '12 at 07:15
  • Starting with PHP 5.3, a shorter version of the ternary operator is available, so you could write: `$a= @$_GET['a'] ?: "default";` - which is almost equivalent to `a = something || 'default';` in javascript (except that it may raise an E_NOTICE error, therefore i added an `@`). Starting with PHP7 you can use the fully equivalent null coalesce operator: `$a= $_GET['a'] ?? "default";` – Philzen Jan 19 '17 at 16:41

3 Answers3

2

I think a ternary if is your best bet here.

In this case I would use isset check - to determine if the key is set and is not null:

$a = isset($_GET['a']) ? $_GET['a'] : "default"

The or operator || doesn't work to null coalesce like that in PHP, but you might have seen it in JavaScript where it can be used to set a value to the first non-false result:

e.g

var a = get['a'] || 'default';
Philzen
  • 2,653
  • 23
  • 34
benedict_w
  • 3,385
  • 1
  • 30
  • 46
0

Refer this PHP shorthand if/else (ternary) information in http://davidwalsh.name/php-ternary-examples

and also

http://davidwalsh.name/learning-ternary-operators-tips-tricks

Prasath Albert
  • 1,407
  • 10
  • 19
  • Not just link. They disappear over time. Add the code-examples. Otherwise just leave a comment with the links. – hakre Oct 22 '12 at 07:17
0

Well, people here doesn't seem to bother reading the entire question this late.

That sintax you wrote works on some other languages but apparently not on php. I think you should just stick to the ternary operator or write a function for that as a shortcut if you're going to use this kind of verification a lot on your page.

function GET($v, $default)
{
    return !isset($_GET[$v]) || empty($_GET[$v]) ? $default : $_GET[$v];
}

$a = GET("a", "default");
Delta
  • 4,098
  • 2
  • 26
  • 36