PHP: Default Variable

Take the CGI variable ‘a’, or if it doesn’t exist, set it to 10.

My version:

if ($_REQUEST['a']=='') $a=10; else $a=$_REQUEST['a'];

Who has a shorter version?


Answer 1, authority 100%

Ternary expression:

$a = ( $_REQUEST['a'] == '' ) ? 10 : $_REQUEST['a'];
//  :
$a = ( ( $a = $_REQUEST['a'] ) == '' ) ? 10 : $a;
// :
$a = $_REQUEST['a'];
if ( $a == '' ) $a = 10;
//   PHP,  JS :
$a = ( $_REQUEST['a'] == '' && 10 ) || $_REQUEST['a'];
$a = ( ( $a = $_REQUEST['a'] ) == '' && 10 ) || $a;
$a = $_REQUEST['a'] || 10;

Remove all optional spaces:

  1. 42
  2. 36
  3. 34
  4. 44
  5. 37
  6. 22

Options 4-6 are not suitable for PHP!!!


Answer 2, authority 67%

//  : 
//   ..      
function v(&$var, $alt = false) { return !empty($var) ? $var : $alt; }
//  :
$a = v($_REQUEST['a'], 10);

Well, ok, try it, but be careful with this one 😉

$a = @$_REQUEST['a'] or $a = 10;

Answer 3, authority 33%

$a = @$_REQUEST['a'] ?: 10;