1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. This forum has been archived. New threads and replies may not be made. All add-ons/resources that are active should be migrated to the Resource Manager. See this thread for more information.

Use in_array() Instead of Multiple <xen:if> Where Appropriate

Discussion in 'Tips and Guides [Archive]' started by James, Mar 12, 2011.

  1. James

    James Well-Known Member

    I've seen people do something like:
    Code:
    <xen:if is="{$user.user_id} == 1">
        //doThis
    </xen:if>
    
    <xen:if is="{$user.user_id} == 2">
        //doThisAgain
    </xen:if>
    
    <xen:if is="{$user.user_id} == 3">
        //doThisAgain
    </xen:if>
    
    As you can see, this is just repeating the same code over and over again which is redundant because you're performing the same function for each check you're doing on the user ID.

    You can minimise this code (and in turn make it more flexible) by doing:
    Code:
    <xen:if is="in_array({$user.userid}, array(1,2,3))">
        //doThis
    </xen:if>
    
    This does exactly the same as my first example. What are the advantages?
    1. Size: The in_array() method is a third of the size of the repeated if statements.
    2. Flexibility: Instead of creating a whole new <xen:if>, you can just add another user ID to array(1,2,3).
    3. Readability: It's much easier to read the in_array() method than spend 3x longer reading the multiple <xen:if> statements.
     
    CyberAP, tenants, cclaerhout and 5 others like this.

Share This Page