-1

I need to come up with a code that would give me the same effect as in the code below

$var1 = "some value"; 
$var2 = "another value"; 
$var3 = 'third value and' . if (isset($var2)) { $var2 } . ' rest of the value';

The above code will result in the following error

syntax error, unexpected 'if' (T_IF)

is there a workaround for something like this? Thanks.

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • 2
    use ternary operator. (isset($a)) ? $var2 : null. But you can use new coalescing operator ?? if value is null or default eg. $var2 ?? null. If you use php 7+ – daremachine Aug 26 '18 at 13:30
  • Why not just set a variable before and have it be empty if not set? – user3783243 Aug 26 '18 at 13:40

2 Answers2

1

By using the ternary operator you can achieve your goal.

<?php
  $var1="some value"; 
  $var2="another value"; 
  $var3= 'third value and' . ((isset($var2)) ? ' ' .$var2 . ' ':' ') . 'rest of the value';
  echo $var3 // output: third value and another value rest of the value
?>

Note: you should surround all the ternary operator expresion by parentheses, otherwise, it will not work as intended. Also, keep in mind ternary operator accepts only one expression to be executed in the true/false conditions.

Like this:

((isset($var2)) ? ' ' .$var2 . ' ':' ')
ThS
  • 4,597
  • 2
  • 15
  • 27
0

As the comment above noted, use a ternary operator to in-line this if statement:

$var3 = 'third value and' . (isset($var2) ? $var2 : '') . ' rest of the value';

You need to decide what you want to put after the semicolon if $var2 isn't set; I just put two quotes, meaning it will print nothing.

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
FoulFoot
  • 655
  • 5
  • 9
  • Thank you, this worked. I don't understand the usage of the () around the isset, though. Can you explain that, please? will accept as answer when the site allows me in a couple of minutes. – Marwan Alkhalil Aug 26 '18 at 13:42
  • The ternary operator "grammar" requires parentheses around the expression to be evaluated. Without them, the "?" wouldn't know what exactly you wanted to evaluate. – FoulFoot Feb 01 '19 at 02:13