PHPLover
PHPLover

Reputation: 12957

In smarty, how to check whether an associative array is empty or not?

I done google for it, but couldn't get the correct solution. Can any one help me out to check whether the associative array is empty or not. Thanks in Advance.

Upvotes: 5

Views: 21327

Answers (3)

Markus
Markus

Reputation: 4689

In Smarty3, you can use PHP's empty() function:

somefile.php

<?PHP
$smarty->assign('array',array());
$smarty->display('template.tpl');

template.tpl

{if empty($array)}
  Array is empty
{else}
  Array is not not empty
{/if}

Outputs Array is empty.

Upvotes: 11

jgabriel
jgabriel

Reputation: 555

It seems that Smarty just check if array exists. For example

somefile.php

<?PHP
$smarty->assign('array',array());
$smarty->display('template.tpl');

template.tpl

{if $array}
  Array is set
{else}
  Array is not set
{/if}

Outputs Array is set.

While in php...

<?PHP
$array = array();
if($array){
  echo 'Array is set';
}else{
  echo 'Array is not set';
}

outputs Array is not set.

To solve this, i made a little workaround: created a modifier for smarty with the following code: modifier.is_empty.php

<?PHP
function smarty_modifier_is_empty($input)
{
    return empty($input);
}
?>

Save that snippet in your SMARTY_DIR, inside the plugins directory with name modifier.is_empty.php and you can use it like this:

template.tpl ( considering using the same somefile.php )

{if !($array|is_empty)}
  Array is not empty
{else}
  Array is empty
{/if}

This will output Array is empty.

A note about using this modifier agains using @count modifier:
@count will count the amount of elements inside an array, while this modifier will only tell if it is empty, so this option is better performance-wise

Upvotes: 3

guessimtoolate
guessimtoolate

Reputation: 8642

You can put the variable directly in an if-statement as long as you're sure it'll be always set (empty or not) like so {if !$array}. If you're looking for something akin to a ternary operator you could use variable modifier called default eg. $array|default:"empty". There's also some help in smarty docs and on their forum. Using PHP's empty also worked for me.

Upvotes: 0

Related Questions