2

Probably a stupid question, but how is best to handle a variable that gets created by an if statement in PHP?

So, the below code would work but if I changed the number 10 to 30 then the if statement would be false and $class would be undefined, which would throw an error.

What is the best way to handle this? Should I just define $class as null before my if statement?

if( 10 < 20 ) {
  $class = 'less';
}

echo '<div class="number ' . $class . '">10</div>';
1
  • You should define $class="" before if statement Commented Oct 10, 2019 at 9:29

5 Answers 5

3

You can use a ternary operation here combined with empty():

if( 10 < 20 ) {
    $class = 'less';
}

echo '<div class="number ' . (!empty($class) ? $class : '') . '">10</div>';

Note that whilst it's preferred to check if something exists before using it, your current code is fine. PHP will throw a notice about usage of undefined index, but it wouldn't fatal error.

However, I'd still recommend checking using empty() - much better to have perfect code that PHP won't throw errors/notices for.

Sign up to request clarification or add additional context in comments.

Comments

2

Handle Like this. Yes You Should to define $class as null before if statement..

$class = "";
if( 10 < 20 ) {
    $class = 'less';
  }

  echo '<div class="number ' . $class . '">10</div>';

1 Comment

Agree with this answer, much easier to read than a inline ternary inside a echo.
1

You can use null-coalescing operator with parentheses to avoid undefined variable error:

if( 10 < 20 ) {
  $class = 'less';
}

echo '<div class="number ' . ($class ?? '') . '">10</div>';

$class ?? '' is a short-form syntax for (isset($class) ? $class : '').

Comments

0

You can use PHP isset function, to determine if a variable is declared and is different than NULL:

echo '<div class="number ' . isset($class) ? $class : '' . '">10</div>';

Comments

-1

This is neither bound to PHP, nor to if alone. When a language lets you create variables "on the fly" it is merely an optional feature, not something that will take care for the overall logic.

Create your variables always on that level where you use them. In doubt, do it initially.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.