How do I condense this code?

Matt C.

Well-known member
What's the best way to condense this piece of code? Is there a way to put them all together?

PHP:
if ($nick === null) {
  $nick = 'null';
}

if ($role === null) {
  $role = 'null';
}

if ($topicUrl === null) {
  $topicUrl = 'null';
}

Thank you!
 
Don't think it is the best way, but one way:

PHP:
$vars = ['nick', 'role', 'topicUrl'];

foreach ($vars as $var) {  if ($$var == null) $$var = 'null'; }

Or even shorter with PHP 7+
PHP:
$vars = ['nick', 'role', 'topicUrl'];

foreach ($vars as $var) $$var = $$var ??  'null';
 
Last edited:
Don't think it is the best way, but one way:

PHP:
$vars = ['nick', 'role', 'topicUrl'];

foreach ($vars as $var) {  if ($$var == null) $$var = 'null'; }

Thank you Kirby. When I run the cron entry, I get an array to string conversion error
Code:
$nullVars = ['nick', 'role', 'topicUrl'];

foreach ($nullVars as $nullVar) {
  if ($$nullVars == null) $$nullVar = 'null';
}
 
Top Bottom