In smarty, how to check whether an associative array is empty or not?
Solution 1
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
.
Solution 2
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
PHPLover
Updated on June 28, 2022Comments
-
PHPLover almost 2 years
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.