Forums / Developer / Appending an array with a concatenated string of variables

Appending an array with a concatenated string of variables

Author Message

Mark Yasuda

Tuesday 12 April 2011 8:44:29 am

Hi there,

I'm new to eZ Publish, but well versed in PHP.
I'm currently working in a template file and struggling somewhat with the syntax / rules, I wonder if someone might be able to help?

I have defined an empty array;

{def $names = array()}

at the top of my particular template file.
I then have a bunch of stuff outputting in HTML, and finally a foreach loop as follows;

{foreach $some_objects as $index => $rel_objects }
  {if eq( $rel_objects.class_identifier, 'speaker' )}
    {$names|append( concat( $rel_objects.data_map.first_name.content , ' ' , $rel_objects.data_map.last_name.content ) ) }
  {/if}
 {/foreach}
 {if gt( $names|count() , 0 )}
  {$names|implode( ', ' )}
 {/if}

My problem seems to be that the concatenation is incorrectly done, as I end up echoing $names as "Array Array Array ..." etc... (note, without any seperating commas!?...)

Any help would be appreciated here, I have no idea why the $rel_objects.data_map.first_name.content is being echo'd as an array when;

{$rel_objects.data_map.first_name.content}

outputs a string (as expected).

Thanks!

André R.

Tuesday 12 April 2011 1:33:42 pm

append does not change the array, it generates a new array. So you need to use se:

{set $names = $names|append(....)}

eZ Online Editor 5: http://projects.ez.no/ezoe || eZJSCore (Ajax): http://projects.ez.no/ezjscore || eZ Publish EE http://ez.no/eZPublish/eZ-Publish-Enterprise-Subscription
@: http://twitter.com/andrerom

Mark Yasuda

Wednesday 13 April 2011 1:27:27 am

That's great, thanks André!
The documentation seems a little confusing regarding this, I'll add a comment to it so hopefully others may benefit.

Thanks again,

Mark

edit: seems like documentation comments were locked down due to spamming.
oh well... maybe someone from eZ docs team will see this and expand on the array append page to reflect that the array does not modify the original input array. Perhaps another example as below:

Example 3

{set $foo = array( 1 , 2 , 3 )}
{set $bar = array( 'red' , 'blue' , 'green' )}
{set $result = $foo|append( $bar )}

Array $result contains: ( 1, 2, 3, 'red', 'blue', 'green' ).