-1

I am trying to pass through a variable to a new name if it is set, or get a POST variable if the first variable is not set.

This is my code but it is not working:

if (isset($randombg)) {
    $background = $randombg;    
} else {  
   $background = $_POST['bg']) 
};

What is wrong with it, or how can I fix this?

Tomasz Kowalczyk
  • 10,472
  • 6
  • 52
  • 68
Carter Roeser
  • 360
  • 3
  • 23

3 Answers3

1

You have typos in your code. There is a ) in $background = $_POST['bg']) and a semicolon

you this should work:

$defaultbg = '#FFFFFF';

if (isset($randombg)) {
    $background = $randombg;    
} elseif( isset( $_POST['bg'] ) ) {  
   $background = $_POST['bg'];
   }else{
       $background = $defaultbg;
       }
Mike Aron
  • 550
  • 5
  • 13
1

[Feature] PHP 7.0.x +

If you are using PHP 7.0.x+ you can use following syntax:

$background = $randombg ?? $_POST['bg'];

In this case $background will get value from first variable which is set and is not null.

You can do even something like this:

$background = $randombg ?? $_POST['bg'] ?? 'No background given'; 
// if $randombg and $_POST['bg'] will be not set or null $background will become 'No background given'

More about that feature you can read in PHP RFC: Null Coalesce Operator and PHP: New Features

About your code

You have syntax in your code. More informations below:

if (isset($randombg)) {
    $background = $randombg;    
} else {  
   $background = $_POST['bg']) // you have syntax here, delete )
}

You can also use short syntax:

$background = (isset($randombg)) ? $randombg : $_POST['bg'];

And it works as follows:

$background = (condition) ? 'when true' : 'when false';

More about it you can read here (Shorthand if/else)

Community
  • 1
  • 1
Karol Gasienica
  • 2,825
  • 24
  • 36
0

Mauybe $randombg is null or empty (that does not exactly means that is not set).

Try this:

if ($randombg) {
    $background = $randombg;    
} else {  
    $background = $_POST['bg'];
}

Or a shorten syntax:

$background = null == $randombg
    ? $_POST['bg']
    : $randombg;
sensorario
  • 20,262
  • 30
  • 97
  • 159