9

I have an array that looks like this:

array(
    'name1' => array('city1', 'city2', 'city3'),
    'name2' => array('city1', 'city4'),
    'namen' => array('city1', 'city7', 'cityn')
);

Which is passed to smarty as : $my_names There is a loop in my Smarty template that looks like this:

{{foreach from=$names item=name}}
  {{foreach from=$cities item=city}}
  //Check if name1 exist and after check if the city is in the array for that name
  {{/foreach}}
{{/foreach}}

I fail to see how would I use the $name and $city to access the array $my_names

I have tried doing if($my_names.$name.$city), but it doesn't work.

shadyyx
  • 15,825
  • 6
  • 60
  • 95
Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

2 Answers2

21

This notation will work too :

{if 'needle'|array_key_exists:$haystack}
....
{/if}
Lucas
  • 16,930
  • 31
  • 110
  • 182
Brice Favre
  • 1,511
  • 1
  • 15
  • 34
13

You can use the array_key_exists() function to check whether the key is in the array.

{if array_key_exists('needle', $haystack)} 
    DoSomethingAboutIt 
{/if}
Daniël W. Crompton
  • 3,448
  • 25
  • 26