02.9b: More Arrays

Let's dig deeper into arrays and see how they can benefit us and make out programs easier to manage.


https://www.youtube.com/watch?v=X-Hb2-q5Ck4





<?php
# * ------------------------------------------------------------
# * Multidimensional arrays

$items[0][0] = "item number";
$items[0][1] = "item name";
$items[0][2] = "price";
$items[0][3] = "stock qty";

$items[1][0] = 15;
$items[1][1] = "stapler";
$items[1][2] = 10.95;
$items[1][3] = 26;

$items[2][0] = 18;
$items[2][1] = "paste";
$items[2][2] = 4.95;
$items[2][3] = 15;

$items[3][0] = 20;
$items[3][1] = "printer paper";
$items[3][2] = 22.95;
$items[3][3] = 50;

print_r( $items );

# * Exercise: Make a program with a two dimensional array containing: name, age, email, and zip code.  
/*
james, 26, james@fakeemail.com, 90210
rebecca, 32, becca@fakeemail.com, 90212
linda, 22, linda@fakeemail.com, 90210
jenna, 27, jenna@fakeemail.com, 90223
bill, 20, bill@fakeemail.com, 90212
*/

# * Print the info for each person who's age is 30 or older.

# * Exercise: Mine Grid
# * Write a program that creates an 10 x 10 grid with some squares having mines (1 in 10 chance).  Hint: Look up the rand() function on php.net.
# * Then print the grid using an astericks '*' to display a mine, and minus sign '-' for no mine, use vertical bars at the start and end of each row.
Example output:
|----------|
|-----*----|
|-*-----*--|
|----------|
|---------*|
|---*----*-|
|----------|
|--*-----*-|
|----------|
|*---------|




# * ------------------------------------------------------------
# * Associative arrays (hashes)

$user['name'] = "Jeff";
$user['email'] = "jeff@fakeemail.com";
$user['age'] = 36;
$user['zip'] = 90210;
$user['phone'] = "925-555-1212";

print_r( $user );

# * Exercise: Create an associative array that contains the names and ages of James, Rebecca, and Linda.  And print the values for anyone over the age of 30.





# * ------------------------------------------------------------
# * foreach

$arr = array(1, 2, 4, 3, 6, 8);

foreach ($arr as $value)    {
    print "value: $value\n";
}

foreach ($arr as &$value)    {
    $value = $value + 1;

    print "value: $value\n";
}

unset( $value );


# * Exercise: Create an array of email addresses then print it using a foreach loop.
# * $emails = array("dave@fakeemail.com", "eric@fakeemail.com", "linda@fakeemail.com", "james@fakeemail.com", "jennifer@fakeemail.com", "lisa@fakeemail.com");

?>