Forums / Setup & design / How to assign a value to a single array element?

How to assign a value to a single array element?

Author Message

E Hoelzler

Saturday 30 December 2006 3:21:04 am

The following code shows, how I tried to modify single elements of an array and the result.

{def $myarray=array(5,7,9)}
myarray = {$myarray[0]}, {$myarray[1]}, {$myarray[2]}<br>
or: {$myarray.0}, {$myarray.1}, {$myarray.2}<br>
loop display:<br>
{foreach $myarray as $ma}
  myarray-element: {$ma}<br>
{/foreach}
{set $myarray.0=20}  {* WHY DOESNT IT WORK?*}
now the array is destroyed<br>
myarray = {$myarray[0]}, {$myarray[1]}, {$myarray[2]}<br>
{foreach $myarray as $ma}
  myarray-element: {$ma}<br>
{/foreach}
{* result not better using an associative array*}
{def $myassocarray=hash('first', 'a',
			'second', 'b',
			'third', 'c')}

myassocarray = {$myassocarray.first}, {$myassocarray.second}, {$myassocarray.third}<br>
myassocarray(alt) = {$myassocarray[first]}, {$myassocarray[second]}, {$myassocarray[third]}<br>
{set $myassocarray.first='x'}

myassocarray(changed) = {$myassocarray.first}, {$myassocarray.second}, {$myassocarray.third}

The result was:

myarray = 5, 7, 9
or: 5, 7, 9
loop display:
myarray-element: 5
myarray-element: 7
myarray-element: 9

now the array is destroyed
myarray = , , 
myassocarray = a, b, c
myassocarray(alt) = a, b, c
myassocarray(changed) = , , 

Claudia Kosny

Tuesday 02 January 2007 2:11:58 pm

Hi E

As you most likely have found out by now assigning a new value to an array element is not possible directly. This fact is hidden quite well in the docu:

The "set" function can not be used to change the value of an element/attribute of an array, hash or an object. In fact, the elements/attributes of arrays, hashes and objects can not be changed from within template code.

http://ez.no/doc/ez_publish/technical_manual/3_8/templates/the_template_language/variable_usage

So best write yourself a custom template operator that does the job, it is really easy to do. First check the contribution section though, maybe there is already such an operator there.

Claudia

kracker (the)

Tuesday 02 January 2007 10:14:10 pm

interesting, it might take a person a long time to clearly see that end. that's worth documenting more clearly.

//kracker

Member since: 2001.07.13 || http://ezpedia.se7enx.com/

E Hoelzler

Wednesday 03 January 2007 12:04:04 pm

Hi Claudia, thank you for your hint - Indeed - I have read that part of the documentation several times. And I didn't recognize those tiny little sentences. And kracker is right: It took me quite a time to get to this point.
What I ACTUALLY wanted to do, I will realize now using a custom event.

Thanks for help

Erwin

Betsy Gamrat

Wednesday 24 January 2007 5:34:25 pm

http://ez.no/doc/ez_publish/technical_manual/3_8/reference/template_operators/arrays/insert