---
schema_version: "1"
id: 994de063d4b57688b49087a6d36bd7a7ccbca35fc7cfbd955fd04cadcfe634de
title: Get Started with AMPscript Development—Lesson 4
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/marketing-cloud/ampscript/guide/get-started/mc-ampscript-get-started-learning-lesson-4.md
canonical_url: https://developer.salesforce.com/docs/marketing/marketing-cloud-ampscript/guide/mc-ampscript-get-started-learning-lesson-4.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: a267274923d66a759f0b17abe6737ef286427893b7d9a2d35cf916a5b16f7c62
products:
  - AMPscript for Marketing Cloud
  - Marketing Cloud
---
# Get Started with AMPscript Development—Lesson 4

This lesson expands on [Lesson 3](https://developer.salesforce.com/docs/marketing/marketing-cloud-ampscript/guide/mc-ampscript-get-started-learning-lesson-3.md), exploring advanced AMPscript topics.

- Using For loops
- Dynamically changing the appearance of a message using AMPscript
- Filtering message context

In addition to the sendable data extension and ShipTime data extension from the previous lessons, this example refers to a data extension that contains information about a subscriber’s purchase history.

## Message Content

This code example contains the message content for this lesson.

```
%%[
  Var @memid,
      @fname,
      @lname,
      @prefname,
      @address,
      @city,
      @state,
      @postcode,
      @mempref,
      @plat,
      @rows,
      @row,
      @ship,
      @shipDays

  Set @memid = MemberID
  Set @fname = FirstName
  Set @lname = LastName
  Set @prefname = PrefName
  Set @address = Address
  Set @postcode = PostalCode
  Set @mempref = MemPref
  Set @plat = Plat
]%%

/* Address the subscriber by their preferred name, if they have one. Otherwise,
   use their first name. */
Hello %%= Iif(Empty(@prefname), @fname, @prefname) =%%, here are your account details.

Name

First Name:%%= v(@fname) =%%
Last Name:%%= v(@lname) =%%
/* Include the PrefName field if it's populated. */
%%[ If not Empty(@prefname) then ]%%
Preferred Name:%%= v(@prefname) =%%
%%[ EndIf ]%%

Address

Address:%%= v(@address) =%%

%%[
  /* Check to see if the postal code field is populated. */
  If not Empty(@postcode) then

    /* Find the postal code in the ShipTimes Data Extension */
    Set @rows = LookupRows("ShipTimes","postcode",@postcode)

    /* Count the number of rows returned to make sure that there's only one match. */
    If RowCount(@rows) == 1 then

      /* Expose all columns in the matching row to the @row variable. */
      Set @row = Row(@rows,1)

      /* Set the @city variable to the value in the city column of the matching row. */
      Set @city = Field(@row,"city")

      /* Set the @state variable to the value in the state column. */
      Set @state = Field(@row,"state")

      /* Set the @ship variable to the value in the ShipTime column. */
      Set @ship = Field(@row,"ShipTime")

    EndIf
  EndIf
]%%

City:%%= v(@city) =%%
State:%%= v(@state) =%%
Postal Code:%%= v(@postcode) =%%

%%[
  /* If we found a shipping time, show it. */
  If not Empty(@ship) then
    /*
    Iif(@ship > 1, Concat(@ship, " days"), Concat(@ship, " day"))
]%%

Shipping Time: %%= v(@shipDays) =%%

%%[ Else ]%%
/* A shipping estimate wasn't available. */

We couldn't find a shipping preference.
Update %%= RedirectTo(Concat('http://example.com?s=',_subscriberkey)) =%% update your profile.

%%[ EndIf ]%%

Member Preferences

Shopping Preference: %%= v(@mempref) =%%

/* Check the subscriber's platinum status and show the appropriate message. */
Platinum Member: %%[ If @plat == "N" then ]%%
%%= RedirectTo(Concat('http://example.com?s=',_subscriberkey)) =%%
Sign-Up
%%[ Else ]%%
%%= v(@plat) =%%
%%[ EndIf ]%%

Recent Purchases

%%[
  /* Declare additional variables for products. */
  Var @prodID, @prodName, @prodDesc, @price, @indicator, @color,
      @totalPurchases, @decimalChar

  /* Set the total purchases to zero. */
  Set @totalPurchases = 0

  /* Set the CSS color indicator to odd. */
  Set @indicator = "odd"

  /* Find all of the recent purchases for the current subscriber.
     Set the @rows variable to contain the resulting rowset. */
  Set @rows = LookupRows("Purchases", "MemberID", @memID)

  /* Make sure that the lookup returned at least one row of products. */
  If RowCount(@rows) >= 1 then

    /* Use a For loop to step through each row in the rowset. */
    For @i = 1 to RowCount(@rows) do

      /* Set the @row variable to contain the data in the current row. */
      Set @row = Row(@rows, @i)

      /* Set the product variables to equal the values in the current row. */
      Set @prodID = Field(@row, "ProductID")
      Set @prodName = Field(@row, "ProductName")
      Set @prodDesc = Field(@row, "Description")
      Set @price = Field(@row, "Price")
      Set @totalPurchases = Add(@totalPurchases, Field(@row, "Price"))

      /* If the value of the indicator variable is "odd", use a white background color.
         After setting the color, change the indicator to "even".*/
      If @indicator == "odd" then
        Set @color = "#FFFFFF"
        Set @indicator = "even"

      /* If the value of the indicator variable is "even", use a gray background color.
         After setting the color, change the indicator to "odd". */
      Else
        Set @color = "#EEEEEE"
        Set @indicator = "odd"
      EndIf

/* Bring in a content area to contain the recent purchase list. */
]%%

%%= TreatAsContent(ContentBlockByName("Content Builder\RecentPurchases")) =%%

%%[
  /* Go to the next row in the rowset. */
  Next @i

  /* Determine if there are two characters after the decimal point. */
  Set @decimalChar = Subtract(Length(@totalPurchases),IndexOf(@totalPurchases,"."))

  /* Handle the case where there's one character after the decimal point. */
  If @decimalChar == 1 then
    Set @totalPurchases = Concat(@totalPurchases,"0")

  /* Handle the case where there's no decimal point. */
  ElseIf @decimalChar == Length(@totalPurchases) then
    Set @totalPurchases = Concat(@totalPurchases,".00")
  EndIf
]%%

Total Purchases:$%%= v(@totalPurchases) =%%

%%[ EndIf ]%%
```

## Create New Variables

The first part of this code example is similar to the example in lesson 3. However, the second part inserts information about the subscriber’s previous purchases and total amount spent into the email.

First, the code creates a set of variables to use in inserting product and price information into the email.

```
/* Declare additional variables for products. */
Var @prodID, @prodName, @prodDesc, @price, @indicator, @color,
    @totalPurchases, @decimalChar
```

Next, the code assigns values to the `@totalPurchases` and `@indicator` variables. The `@totalPurchases` variable stores the amount of the subscriber’s total purchases. The `@indicator` variable alternates the background color for each purchase.

```
/* Set the total purchases to zero. */
Set @totalPurchases = 0

/* Set the CSS color indicator to odd. */
Set @indicator = "odd"
```

## Look Up Data in a Data Extension

The code consults the Purchases data extension to find all of the subscriber’s previous purchases based on their member ID.

```
Set @rows = LookupRows("Purchases", "MemberID", @memID)
```

The `@rows` variable is set to the resulting rowset.

## Use a For Loop to Iterate through the Rowset

If there aren’t any rows in the rowset, it means that there isn’t any purchase data to display. We want to be sure that the rowset contains at least one row, so we use the [RowCount()](/docs/marketing/marketing-cloud-ampscript/references/mc-ampscript-data-extension/mc-ampscript-reference-data-extension-row-count.html) function.

```
  If RowCount(@rows) >= 1 then
```

Next, the code uses a [For loop](https://developer.salesforce.com/docs/marketing/marketing-cloud-ampscript/language-basics/mc-ampscript-guide-language-basics-for-loops.md) to step through the rowset that we obtained from the data extension. The For loop repeats an equal number of times to the number of rows in the rowset.

```
For @i = 1 to RowCount(@rows) do
```

The [row()](/docs/marketing/marketing-cloud-ampscript/references/mc-ampscript-data-extension/mc-ampscript-reference-data-extension-row.html) function obtains the data in all of the columns in the current row.

```
Set @row = Row(@rows, @i)
```

In each row, we use the [Field()](/docs/marketing/marketing-cloud-ampscript/references/mc-ampscript-data-extension/mc-ampscript-reference-data-extension-field.html) function to set the values of the product variables. We also use the [Add()](/docs/marketing/marketing-cloud-ampscript/references/mc-ampscript-math/mc-ampscript-reference-math-add.html) function to keep a running total of the amount of money the subscriber spent on their purchases.

```
Set @prodID = Field(@row, "ProductID")
Set @prodName = Field(@row, "ProductName")
Set @prodDesc = Field(@row, "Description")
Set @price = Field(@row, "Price")
Set @totalPurchases = Add(@totalPurchases, Field(@row, "Price"))

```

## Change the Appearance of Each Row

The cod sets the background color for the current row to white or gray depending on the background color of the previous entry. Odd-numbered entries have a white background, and even entries have a gray background.

```
If @indicator == "odd" then
  Set @color = "#FFFFFF"
  Set @indicator = "even"

/* If the value of the indicator variable is "even", use a gray background color.
    After setting the color, change the indicator to "odd". */
Else
  Set @color = "#EEEEEE"
  Set @indicator = "odd"
EndIf
```

## Apply the Content to a Contact Area

The code uses the [ContentBlockByName()](/docs/marketing/marketing-cloud-ampscript/references/mc-ampscript-content/mc-ampscript-reference-content-block-by-name.html) function to retrieve an existing content block. The purchase data is formatted in the same manner as the content block.

```
%%= TreatAsContent(ContentBlockByName("Content Builder\RecentPurchases")) =%%
```

The code then instructs the For loop to proceed to the next row.

```
%%[ Next @i ]%%
```

## Format the Currency Value

The final part of the code makes sure that the numerical value in the `@totalPurchases` variable contains exactly two decimal places. It starts by determining the current number of decimal places by using the [IndexOf()](/docs/marketing/marketing-cloud-ampscript/references/mc-ampscript-string/mc-ampscript-reference-string-index-of.html), [Length()](/docs/marketing/marketing-cloud-ampscript/references/mc-ampscript-string/mc-ampscript-reference-string-length.html), and [Subtract()](/docs/marketing/marketing-cloud-ampscript/references/mc-ampscript-math/mc-ampscript-reference-math-subtract.html) functions.

- The `IndexOf(@totalPurchases,".")` function returns the position in the value of the `@totalPurchases` variable where a decimal point (.) character occurs. If the variable doesn’t contain a decimal point, the function returns `0`.
- The `Length(@totalPurchases)` function returns the number of characters in the value of the `@totalPurchases` variable.
- The `Subtract(...)` function returns the result of subtracting the value returned by the `IndexOf(...)` function from the value returned by the `Length(...)` function.

```
Set @decimalChar = Subtract(Length(@totalPurchases),IndexOf(@totalPurchases,"."))
```

If the resulting value of this computation is `1`, it means that the value of the `@totalPurchases` contains a decimal point followed by one digit. Because we want to show the subscriber a currency value with two decimal places, we use the [Concat()](/docs/marketing/marketing-cloud-ampscript/references/mc-ampscript-string/mc-ampscript-reference-string-concat.html) function to add a zero to the end of the value.

```
If @decimalChar == 1 then
  Set @totalPurchases = Concat(@totalPurchases,"0")
```

If the value of the `@decimalChar` variable equals the number of characters in the value of the `@totalPurchases` variable, it means that the `@totalPurchases` didn’t contain a decimal point. In this case, we can use the `Concat()` function to add a decimal point followed by two zeros.

```
ElseIf @decimalChar == Length(@totalPurchases) then
  Set @totalPurchases = Concat(@totalPurchases,".00")
EndIf
```
