## CS637 Practice on Arrays: Solution

Example of ordinary array from text, pg. 315:
```\$names = array('Ted Lewis', 'Sue Jones', 'Ray Thomas');```
Here \$names[0] is 'Ted Lewis'; etc.

1. Create an array named \$fruits with strings "apple", "pear", and "berries"

\$fruits = array('apple', 'pear', 'berries'); // or use double quotes

2. Add another fruit name to the array

\$fruits[] = 'bananas';

Example of associative array from text, pg. 321
```\$tax_rates = array('NC' => 7.75, 'CA' => 8.25, 'NY' => 8.875)'```

3. What is \$tax_rates['CA']?     8.25    count(\$tax_rates)?  3

4. Add another element to \$tax_rates for state 'MA', rate 6.25:

\$tax_rates['MA'] = 6.25;

5. Create a shopping cart item named \$item with id 10, name "pencils", price 10.49. This should be an associative array with 3 keys, 3 values.

\$item = array('id'=>10, 'name'=>'pencils', 'price' => 10.49);

6. We can create an empty cart with    ```\$cart = array();```
Write a line of code to put \$item in the cart.

\$cart[] = \$item;

7. Write a loop over the items in \$cart, adding up the prices into \$total_price. Use foreach, as in this example for \$tax_rates:
```foreach (\$tax_rate  as \$rate) {    echo '<li>\$rate</li>'; }```

but in this case the array item is \$item, itself an associative array.

\$total_price = 0;
foreach (\$cart as \$item) {
\$total_price += \$item['price'];
}