S
S
spido2021-06-11 08:34:27
PHP
spido, 2021-06-11 08:34:27

What is the correct way to check for an empty variable?

Greetings!
I wrote a check for an empty variable, but there are doubts about the optimality of the code.

Can you check and suggest how best to check?

$var = isset($editable_page['editable_page_theme_config']['back_color']) && $editable_page['editable_page_theme_config']['back_color']; // проверяет пустая или не пустая переменная. Если не пустая, тогда дает 1
      if($var == '1')  { // если единичка, тогда выводить переменную, если нет, то выводить пустую переменную $string = '';
        $string = $editable_page['editable_page_theme_config']['back_color'];
      } else {
        $string = '';
      }
      $page_back_color = $string;

<p>{$page_back_color}</p>

Thanks in advance to those who respond!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kuznetsov, 2021-06-11
@dima9595

What happens if the editable_page array doesn't have an editable_page_theme_config array inside it ? That's right - everything is broken. You need to first check for the existence of the editable_page_theme_config array , and then try to get the back_color .
Something like this:

return isset($editable_page['editable_page_theme_config']['back_color']) ? $editable_page['editable_page_theme_config']['back_color'] : '';

Or if you don't need to do a return:
$var = isset($editable_page['editable_page_theme_config']['back_color']) ? $editable_page['editable_page_theme_config']['back_color'] : '';

// ... что-то делать с переменной $var дальше

Thanks Lander for the tip.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question