简体   繁体   中英

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.

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM