31

I'm using Smarty template engine.

I'm doing a simple login page. I set a variabile named error with a message if there are some problems, but IF NOT I get:

Notice: Undefined index: error

How could I check if this variable exists?

I only do:

{if $error}<h1>{$error}</h1>{/if}

thanks

Dail
  • 4,622
  • 16
  • 74
  • 109
  • The answers below do not take into account that a variable can be set to `null`. $error may exist and be null, in which case isset($error) returns false. – pwagner Apr 25 '17 at 15:13

4 Answers4

68

There you go!

{if isset($error)}
    {* TODO something *}
{/if}
Daniel Guerrero
  • 184
  • 1
  • 2
  • 8
Wesley van Opdorp
  • 14,888
  • 4
  • 41
  • 59
57

isset() - smarty - php

isset($error)
Wazy
  • 8,822
  • 10
  • 53
  • 98
3

You can also use:

{if $error|default}<h1>{$error}</h1>{/if}

"|default" modifier check if variable exist and accept one param (default: empty string)

r_a_f
  • 629
  • 7
  • 18
-3

This is short :) No warnings or errors.

{if $error}
Dumindu Perera
  • 1,571
  • 15
  • 13
  • 2
    As you could see in the question this produces a notice. I assume you have the errorlevel high enough that you don't see notices. – user2587656 Nov 07 '19 at 15:08
  • In PHP 8.1, the notice has become a warning: `PHP Warning: Attempt to read property "value" on null in [template]`. The compiled code would here be `tpl_vars['error']->value) {?>`, but tpl_vars['error'] wouldn't exist. – Dereckson Feb 05 '22 at 13:05