1 DIG 3134 – Lecture 4: Arrays and Strings Michael Moshell University of Central Florida Media...

Post on 14-Dec-2015

214 views 0 download

Transcript of 1 DIG 3134 – Lecture 4: Arrays and Strings Michael Moshell University of Central Florida Media...

1

DIG 3134 – Lecture 4:

Arrays and Strings

Michael MoshellUniversity of Central Florida

Media Software Design

2

First: Review the Forms Homework

while (answers are not yet enough)

{ foreach ($class as $student)

if ($student is here and awake)

call on $student;

}

3

Array: A filing cabinet, or a LIST of variables.

$price[1]

$price[2]

$price[3]

$price[4]

Variable Name

Index

Value

1

2

3

(whoops)

4

A For-Loop

for ($m=1; $m<=4; $m++){

print “now m is “.$m. “!<br />”;}HAND SIMULATION:value of m: printed output.

5

A For-Loop

For ($m=1; $m<=4; $m++){

print “now m is “.$m. “ !<br />”;}HAND SIMULATION:value of m: printed output.

6

A For-Loop

For ($m=1; $m<=4; $m++){

print “now m is “.$m. “ !<br />”;}HAND SIMULATION:value of m: printed output.1

7

A For-Loop

For ($m=1; $m<=4; $m++){

print “now m is “.$m. “ !<br />”;}HAND SIMULATION:value of m: printed output.1

now m is 1!

8

A For-Loop

For ($m=1; $m<=4; $m++){

print “now m is “.$m. “ !<br />”;}HAND SIMULATION:value of m: printed output.1

now m is 1!2

9

A For-Loop

For ($m=1; $m<=4; $m++){

print “now m is “.$m. “ !<br />”;}HAND SIMULATION:value of m: printed output.1

now m is 1!2

now m is 2!

10

A For-Loop and an array

For ($m=1; $m<=4; $m++){

$list[$m]= 3;}// that will put 3 in each location of $m

print $list[2]; //HAND SIMULATE NOW!value of m printed output

$m $list[$m]1234

11

A For-Loop and an array:Result after loop finishes

For ($m=1; $m<=4; $m++){

$list[$m]= 3;}// that will put 3 in each location of $m

print $list[2]; //HAND SIMULATE NOW!value of m printed output1234 3

$m $list[$m]1 32 33 34 3

12

A For-Loop and an array

For ($m=1; $m<=4; $m++){

$list[$m]= $m;}// that will put $m in each location of $m

print $list[2]; // what will this print?value of m printed output

$m $list[$m]1 12 23 34 4

1313

A For-Loop and an array

For ($m=1; $m<=4; $m++){

$list[$m]= $m;}// that will put $m in each location of $m

print $list[2]; // what will this print?value of m printed output1234 2

$m $list[$m]1 12 23 34 4

1414

A For-Loop and an array

For ($m=1; $m<=4; $m++){

$list[$m]= $m;}// that will put $m in each location of $m

print $list[2]; // what will this print?value of m printed output1234 2

$m $list[$m]1 12 23 34 4

15

A For-Loop and an array

For ($m=1; $m<=4; $m++){

$list[$m]= 2*$m;}

Print $list[3]; // what will this print?

16

A while-Loop and an array(we can go faster now)

$m=1;while ($m<=7){

$list[$m]= 2*$m;$m=$m+2;

}

Print $list[5]; // what will this print?

17

A while-Loop and an array

$m=1;While ($m<=7){

$list[$m]= 2*$m;$m=$m+2;

}

Print $list[4]; // what will this print?

18

And now …

We move to the subject of STRINGS.

19

The Objective:• Learn how to do all kinds of things

with text in PHP• Why? Numbers are pretty dumb;

Almost all good stuff is words.

20

String Constants & Variables

$n=3;$test= "A bear came over $n mountains.";print $test; // what is printed?

21

String Constants & Variables

$n=3;$test= "A bear came over $n mountains.";print $test; // what is printed?A bear came over 3 mountains.

22

String Constants & Variables

$test= "A bear came over $n mountains.";$n=3;print $test; // what is printed?

23

String Constants & Variables

$test= "A bear came over $n mountains.";$n=3;print $test; // what is printed?A bear came over mountains.

24

String Constants & Variables

$test= "A bear came over $n mountains.";$n=3;print $test; // what is printed?A bear came over mountains.

Since nothing had been put into $n,before $test was built,

nothing was printed in that spot.

25

String Constants & Variables

$n=3;$test= 'A bear came over $n mountains.';print $test; // what is printed?

26

String Constants & Variables

$n=3;$test= 'A bear came over $n mountains.';print $test; // what is printed?A bear came over $n mountains.

27

String Constants & Variables

$n=3;$test= 'A bear came over $n mountains.';print $test; // what is printed?A bear came over $n mountains.** because: double quotes are PARSED** but single quotes are NOT PARSED

28

String Constants & Variables

$n=3;$test= 'A bear came over $n mountains.';print $test; // what is printed?A bear came over $n mountains.** because: double quotes are PARSED** but single quotes are NOT PARSED

"Parsed" means – scanned and processed by PHP."Not parsed:" just print exactly what you see.

29

String Constants & Variables

$n=3;$test= 'A bear came over '.$n.' mountains.';print $test; // what is printed?A bear came over 3 mountains.** because: we concatenated threestrings (actually 2 strings and 1 integer.)

Sometimes "The price is $price[$n]" won't work.

But 'The price is '.$price[$n] always works.

30

So, which should I use?

Use single quotes ' ' unless youhave a reason to use " " doubles.

I often embed variables in string constants becauseit's quick and simple (if they're not arrays.)

In that case, I use double quotes. Like

print "The price of coffee is $coffeeprice pesos."; versus

print 'The price of coffee is '.$coffeeprice.' pesos';

31

Concatenation

means 'stick things together'.

$firstname="Mike";$secondname="Moshell";

$name=$firstname.$secondname.

concatenation operatorprint $name;

MikeMoshell

32

ConcatenationHow can I get a space in my name?

$firstname="Mike";$secondname="Moshell";

$name=$firstname.' '.$secondname;

include a spaceprint $name;

Mike Moshell

33

Another way to do it

$firstname="Mike";$secondname="Moshell";

$name="$firstname $secondname";

double quotes let PHP parse the string.print $name;

Mike Moshell

34

Anatomy of a String

$test= "A bear came over 2 mountains.";

Position 0 in the string

In PHP a string variable can be ANY LENGTH!You can put an Encyclopedia in a string.

35

Anatomy of a String

$test= "The cat in the lap.";$nums= "0123456789012345678";

I used a monospaced font (Courier) to make it easier to line up two strings and count the characters.

3636

Anatomy of a String

$test= "The cat in the lap.";$nums= "0123456789012345678";

$piece=substr($test,1,5);Print $piece; // what will this print?

what string

373737

Anatomy of a String

$test= "The cat in the lap.";$nums= "0123456789012345678";

$piece=substr($test,1,5);Print $piece; // what will this print?

what string what starting point

38

how far to copy.

383838

Anatomy of a String

$test= "The cat in the lap.";$nums= "0123456789012345678";

$piece=substr($test,1,5);Print $piece; // what will this print?

what string what starting point

39393939

Anatomy of a String

$test= "The cat in the lap.";$nums= "0123456789012345678";

$piece=substr($test,1,5);Print $piece; // what will this print?

he caStarts in position 1, copies 5 characters

4040404040

Anatomy of a String

$test= "The cat in the lap.";$nums= "0123456789012345678";

$piece=substr($test,4);Print $piece; // what will this print?

414141414141

Anatomy of a String

$test= "The cat in the lap.";$nums= "0123456789012345678";

$piece=substr($test,4);Print $piece; // what will this print?

cat in the lap.When the 'length' is missing, copy ALL the rest.

42

String Position

$test= "The cat in the lap.";$nums= "0123456789012345678";

$p=strpos($test,"cat");print "p=$p <br />";What will this print?

4343

String Position

$test= "The cat in the lap.";$nums= "0123456789012345678";

$p=strpos($test,"cat");print "p=$p <br />";What will this print?4Because the string 'cat' begins at position 4 in $test

4444

Cutting up a String

$test= "The cat in the lap.";$nums= "0123456789012345678";

$p=strpos($test,"cat");print "p=$p <br />";

$before=substr($test,0,$p-1);print "before=$before <br />";

45

Anatomy of a String

$test= "The cat in the lap.";$nums= "0123456789012345678";$p=strpos($test,"cat");print "p=$p <br />";

$before=substr($test,0,$p-1);print "before=$before <br />";

what starting point

46

Anatomy of a String

$test= "The cat in the lap.";$nums= "0123456789012345678";$p=strpos($test,"cat");print "p=$p <br />";

$before=substr($test,0,$p-1);print "before=$before <br />";

how far to copy.

47

Anatomy of a String

$test= "The cat in the lap.";$nums= "0123456789012345678";$p=strpos($test,"cat");print "p=$p <br />";

$before=substr($test,0,$p-1);print "before=$before <br />";

p=4

before=The

48

Challenge #1:

$test= "The fat cat sleeps.";$nums= "0123456789012345678";$p=strpos($test,"cat");print "p=$p <br />";

$before=substr($test,0,$p-1);print "before=$before <br />";

WHAT DOES IT PRINT? Hand simulate now.

49

Anatomy of a String

$test= "The fat cat sleeps.";$nums= "0123456789012345678";$p=strpos($test,"cat");print "p=$p <br />";

$before=substr($test,0,$p-1);print "before=$before <br />";

p=8

5050

Anatomy of a String

$test= "The fat cat sleeps.";$nums= "0123456789012345678";$p=strpos($test,"cat");print "p=$p <br />";

$before=substr($test,0,$p-1);print "before=$before <br />";

p=8

before=The fat

51

The third string-tool:strlen

$test= "The fat cat sleeps.";$nums= "0123456789012345678";$target="fat";

$t=strlen($target);Print "Target is '$target.' ";Print "It has $t characters.";What will this print?

5252

The third string-tool:strlen

$test= "The fat cat sleeps.";$nums= "0123456789012345678";$target="fat";

$t=strlen($target);Print "Target is '$target.' ";Print "It has $t characters.";

Target is 'fat'.It has 3 characters.

53

Challenge #2:

$firstname="Henry";$lastname="Washington";

Task: If total length of $firstname.' '.$lastname is less than 20 characters, print it on one line, like

Henry WashingtonOtherwise print it (centered) on two lines, like

Henry Washington // DO IT NOW //<<HINT: "otherwise" is written as "else" in PHP>>

54

Challenge #2:

$firstname="Henry";$firstname="Washington";

Task: If total length of $firstname.' '.$lastname is < 20 characters, print it on 1 line, else 2 lines

$combined=$firstname.' '.$lastname;if (strlen($combined)<20)

{ print $combined; }else

{ print $firstname.'<br />'.$lastname; }

55

Homework Problem #1

$name="Henry Washington";

Task: If total length of $name is less than 20 characters, print it on one line, like

Henry Washington

Otherwise: use strpos to find ' ' (blank), split into two lines, and print it (centered) on two lines, like

Henry Washington

56

PHP's Power Tools for Strings

You can do everything with strpos, strlen, substr. They are a 'universal tool-kit'. But sometimes it wouldbe VERY tedious, with lots of 'if' statements.

To move into the Power Tools department,we need two additional concepts.

String indexed ("associative") arrays (TODAY)andRegular Expressions (LATER in the SEMESTER)

57

String Indexed Arrays

The old way:$price[1]=14.95;$price[2]=22.95;$price[3]=49.95;

$item[1]='umbrella';$item[2]='raincoat';$item[3]='deluxe raincoat';

item:umbrella1

item:raincoat2

price:14.951

price:22.952

58

String Indexed Arrays

The old way:$price[1]=14.95;$price[2]=22.95;$price[3]=49.95;

$item[1]='umbrella';$item[2]='raincoat';$item[3]='deluxe raincoat';

To find cost_of('raincoat') you used to needa loop and some time (for 100,000 inventory items,average time of 50,000 tests....

"ignorant" programming.)

59

Sequentially searching an array

The old way:$price[1]=14.95;$price[2]=22.95;$price[3]=49.95;$imax=3;

$item[1]='umbrella';$item[2]='raincoat';$item[3]='deluxe raincoat';

$i=1;while ($i<=$imax) && $item[$i] != 'raincoat'){

$i++;}print "price of ".$item[$i]." is ".$price[$i].".";

60

.. and an improvement:report success AND failure

$i=1; $searchterm='raincoat';while ($i<=$imax) && $item[$i] != $searchterm){

$i++;}if ($i<=$imax){ print "price of ".$item[$i]." is ".$price[$i].".";}else{ print "I did not find $searchterm."; }

-- Always plan for failure. --

61

String Indexed Arrays(a.k.a. associative array)

The new way:$price['umbrella']=14.95;$price['raincoat']=22.95;$price['deluxe raincoat']=49.95;

price:14.95

price:22.95 Raincoat

Umbrella

62

String Indexed Arrays

The new way:$price['umbrella']=14.95;$price['raincoat']=22.95;$price['deluxe raincoat']=49.95;

print 'price of '.$item.' is '.$price[$item]. '.';

$item='raincoat';

63

2. Make an associative array. Keys are login IDs,Contents are the corresponding passwords.

Example: $password['joesmith']='squiggle';$password['snookums']='toocute';$password['kittycat']='meowr';

Write code that prints 'ADMIT' if $username matches a key, and $userpass matches the contents. It prints REJECT otherwise.

$username="mikemoshell";$userpass="chocolate fudge"; // reject!

Homework practice problems

64

3. Make two associative arrays, $price and $inventory; key values are 'umbrella', 'raincoat', etc.Data values are price and how-many-in-stock.

Input is $item='raincoat'; Your program checks theinventory. If >0, it prints

The price of raincoats is $14.95. We have 2.If inventory= =0, it prints

Sorry, we're out of raincoats.

Homework practice problems

65

FOR ADVANCED FOLKS:Loops and Associative Arrays

For numerically-indexed arrays, you can getall the contents with a for-loop. example:

for ($i=1; $i<6; $i++) { print $i.' '.$price[$].'<br />'; }

For string-indexed arrays like $password, we use a foreach

foreach ($password as $key=>$value){

print "user=$key and password=$value<br />";}

66

Loops and Associative Arrays

foreach ($mother as $key=>$value){

print "child=$key & mother=$value<br />";}

Array:$mother['Jesus']='Mary';$mother['Mary']='Ann';$mother['Jack']='Mary';$mother['Ann']='Elizabeth';

Printout:child=Jesus & mother=Mary child=Mary & mother=Annchild=Jack & mother=Marychild=Ann & mother=Elizabeth

6767

Put your code for problems 1 and 2 and 3on the previous page into

MAMP or WAMP or sulley and run it.

<?php//Put your code here?>

Be ready to DEMONSTRATE your code working!

Homework practice problems(Everyone)

6868

5. Figure out how to construct a function (next lecture) named grandmother($person), using the $mother array from #4.

If there is enough information to find the grandmother of $person (like Sam), print out

‘Sam’s grandmother is Suzie’.Otherwise print out

‘I don’t know who Sam’s grandmother is.’

EXTRA Problem #1FOR ADVANCED FOLKS

6969

5. Figure out how to construct a function (next lecture) named grandkids($person), using the $mother array from #4.

If Mary has one or more grandchildren, print

“Mary’s grandchildren are Sam and Ed.”Else print

“Mary has no grandchildren.”

EXTRA Problem #2FOR EXTRA ADVANCED FOLKS