user2246968
user2246968

Reputation: 119

Handling Variables within an if statement - PHP

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>';

Upvotes: 2

Views: 111

Answers (5)

Dharman
Dharman

Reputation: 33295

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 : '').

Upvotes: 1

fmsthird
fmsthird

Reputation: 1875

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>';

Upvotes: 0

AmigoJack
AmigoJack

Reputation: 6099

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.

Upvotes: -1

treyBake
treyBake

Reputation: 6560

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.

Upvotes: 3

Vaibhavi S.
Vaibhavi S.

Reputation: 1093

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>';

Upvotes: 2

Related Questions