intro to php - department of electrical engineering...

54
EECS1012 Net-centric Introduction to Computing M.S. Brown, EECS – York University 1 More PHP: Arrays and Files EECS 1012 Acknowledgements Contents are adapted from web lectures for “Web Programming Step by Step”, by M. Stepp, J. Miller, and V. Kirst. Slides have been ported to PPT by Dr. Xenia Mountrouidou. These slides have been edited for EECS1012, York University. The contents of these slides may be modified and redistributed, please give appropriate credit. (Creative Commons) Michael S. Brown, 2017.

Upload: nguyenhanh

Post on 10-Apr-2018

222 views

Category:

Documents


4 download

TRANSCRIPT

EECS1012Net-centric Introduction

to Computing

M.S. Brown, EECS – York University 1

More PHP: Arrays and Files

EECS 1012

Acknowledgements

Contents are adapted from web lectures for “Web Programming Step by Step”, by M. Stepp, J. Miller, and V. Kirst.

Slides have been ported to PPT by Dr. Xenia Mountrouidou.

These slides have been edited for EECS1012, York University.

The contents of these slides may be modified and redistributed, please give appropriate credit.

(Creative Commons) Michael S. Brown, 2017.

Arrays2

Arrays3

<?php$food = array("falafel", "pide", "poutine");print "I like to eat $food[0] and $food[2] ";

?> PHP

An array stores multiple values accessible by a

single variable name

We can access the value sin the array using an

“index” or “key”.

CSEECS 1012

I like to eat falafel and poutine. output

Indexed Arrays4

Index arrays (or numerical arrays) are arrays

where the individual values in the array are access

with a numeric index. Indexing starts at position 0,

not 1.

<?php$food = array("falafel", "pide", "poutine");print "My favorite is $food[0] \n";

?> PHP

0 1 2

"falafel" "pide" "poutine"

[index]

array value

$food

EECS 1012

Indexed array syntax5

$var[ index ]

Array variable name index (sometimes called "offset")

that you want to access

within brackets [ ]

Array() function6

<?php$num = array(100, 90, 80, 70, 60, 50, 40, 30, 20, 10);print $num[0]; # output would be 100

?> PHP

The function array() can be used to create an

array variable as shown above. In this example,

the data in the array are integers.

0 1 2 3 4 5 6 7 8 9

100 90 80 70 60 50 40 30 20 10

[index]

array value

$num

Indexed arrays are similar to how we accessed individual characters in string variables.

Manual array assignment7

<?php$food[0] = "dosa";$food[1] = "pide";$food[2] = "poutine";

print "I like to eat $food[0] and $food[2] ";?> PHP

I like to eat dosa and poutine. output

We can manually assign values to an array.

This example did not use the array function, but the

result is identical.

print_r function8

<?php$array_var = array( "CSS", "PHP", "HTML", "Coding" );

print_r($array_var);

?> PHP

Array

(

[0] => CSS

[1] => PHP

[2] => HTML

[3] => Coding

) output

This function is referred to as the "Print Readable" function and helps you visualize

the contents of your data. You can use it with arrays or other data types.

Appending an array 9

<?php

$a = array("CSS", "HTML", "PHP");$a[] = "Java Script";print_r($a);

?> PHP

Array

(

[0] => CSS

[1] => HTML

[2] => PHP

[3] => Java Script

) output

If you assign a value to an array without an index

specified, e.g. $a[ ] = "Hello", PHP will append the

new value at the "end" of the current array.

EECS 1012

Associative Arrays10

<?php$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");print $age["Peter“];print “\n”;print $age[“Joe”];

?> PHP

35

43output

Associative arrays uses a “key” to access an

individual element in the array.

Syntax: $var_name[ key ]. The key is often a

string, but can also be a numerical value.

Associative array syntax11

$var[ key ]

Array variable name name of the key that you want

to access within brackets [ ]

Associative arrays using array()12

$a = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

key is

a stringvalue is a string

$a = array(1 => "Five", 2 => "Two", 3 => "Three");

key is

a numbervalue is a string

Syntax to specify in the array() function: key => value. You will

generally string values used as keys, but numerical values can also be

used as shown above.

Associative array example13

<?php

$a["lecture"] = "Hall A";$a["labs"] = "William Small 106";$a["university"] = "York";$a["college"] = "Lassonde";

print_r($a); ?> PHP

Array

(

[lecture] => Hall A

[labs] => William Small 106

[university] => York

[college] => Lassonde

)output

You can also manually assign

data to associative arrays.

EECS 1012

Printing array values14

<?php$prez[0] = "Obama";$prez[1] = "Trump";$prez[2] = "Bush";

print "First $prez[2], then $prez[0], now $prez[1] . . \n";PHP

We can print out indexed arrays just like other

variables

First Bush, then Obama, now Trump . . .

output

EECS 1012

Printing array with string keys15

$a["university"] = "York";$a["college"] = "Lassonde";

print "EECS is in the {$a["college"]} college \n";PHP

When we print array values with string keys, we

need to place them within { } in the print statement

EECS 1012

Arrays are used like other variables16

$a = array( 5, 10, 15, 20, 25, 30 ); $a[0] = $a[0] + 10; // $a[0] now equals 15 $a[1]++; // $a[1] now equals 11 $a[2] = $a[3] + $a[5]; // $a[2] now equals 50 print_r($a);

PHP

The math operations in

this example are just like

we saw for non-array

variables in the last lecture notes.

Array

(

[0] => 15

[1] => 11

[2] => 50

[3] => 20

[4] => 25

[5] => 30

) OUTPUT

Arrays are used like other variables17

$a = array( "first" => "Abdel", "last" => "Zhang" );

$anme = $a["first"] . " " . $a["last"];

print "$name \n";

PHP

Abdel Zhang

OUTPUT

In this example the associative array values are accessed using keys. They are

concatenated together (with a space in the middle) to form a larger string.

EECS 1012

Expression breakdown18

EECS 1012

$name = $a["first"] . " " . $a["last"];

"Abdel" . " " . "Zhang";

"Abdel " . "Zhang";

"Abdel Zhang";

(1) access values

from the two

associative arrays

(2) apply the first

concatenation oper-

ator with "Abdel"

and " ".

(3) apply seccond

concatenation oper-

ator with "Abdel "

and "Zhang"

(4) assign result to

variable $name

$name = "Abdel Zhang";

Accessing arrays using variables19

$a = array("Pide", "Dosa", "Falafel", "Poutine");

print "I like the following foods ";for($i=0; $i < 4; $i++){

print "($i) $a[$i] ";} PHP

I like the following foods: (1) Pide (2) Dosa (3) Falafel (4) Poutine output

We can use a variable's value to access the index.

In the above example, $i, is used to access the

values in array $a

count function for arrays20

$a = array("Pide", "Dosa", "Falafel", "Poutine");$a_length = count($a);print "The number of items in the array is $a_length. \n";

PHP

The number of items in the array is 4. output

count(a) returns the number of elements in the array

a. Sometimes we call this the "size" of the array, or

"length" of the array.

EECS 1012

Simple array code example21

<?php

$names = array("Abdel", "Xiong", "Tyler", "Mahsa", "Lili", "Deaner", "Tony", "Saeed");

for($i=0; $i < count($names); $i++){

print "Student $i has name $names[$i] \n";}

PHPStudent 0 has name Abdel

Student 1 has name Xiong

Student 2 has name Tyler

Student 3 has name Mahsa

Student 4 has name Lili

Student 5 has name Deaner

Student 6 has name Tony

Student 7 has name Saeed OutputEECS 1012

Some useful array functions22

Function Description

array_rand(a) Returns a randomly chosen index that is

valid for array a

count(a) returns the number of elements in an array

array_sum(a) Sums up all the values in the array

in_array(val, a) Returns "true" if the given value is found in

the array a

shuffle(a) rearranges the order of an array

sort(a) sorts the contents of array a

array_keys(a) returns an indexed array of all the keys in

an associative array a

EECS 1012

Examples – array_rand()23

<?php

$names = array("Abdel", "Xiong", "Tyler", "Mahsa", "Lili", "Deaner", "Tony", "Saeed");

$lucky = array_rand($names); # selects a random index!

print "$names[$lucky] gets an A for EECS1012 \n";

PHP

Deaner gets an A for EECS1012

EECS 1012

Examples – sort()24

<?php

$names = array("Abdel", "Xiong", "Tyler", "Mahsa", "Lili", "Deaner", "Tony", "Saeed");

sort($names); # this sorts the array, place result back in# the same variable

for($i=0; $i < count($names); $i++){

print "Student $i has name $names[$i] \n";}

PHPStudent 0 has name Abdel

Student 1 has name Deaner

Student 2 has name Lili

Student 3 has name Mahsa

Student 4 has name Saeed

Student 5 has name Tony

Student 6 has name Tyler

Student 7 has name Xiong OutputEECS 1012

Examples – array_keys()25

$items= array("iPhone" => 988, "Samsung" => 700, "LG" => 500);

$keys = array_keys( $items ); # returns an array with the keys from# items

for($i=0; $i < count($keys); $i++) {

$key = $keys[$i]; print "Item: $i Brand: $key Price: $ $items[$key] \n";

}

PHP

Item: 0 Brand: iPhone Price: $ 988

Item: 1 Brand: Samsung Price: $ 700

Item: 2 Brand: LG Price: $ 500

OUTPUT

Examples – in_array()26

$class = array("Abdel", "Mahmoud", "Sam", "Tyler", "Susan", "Kyros");

$find_person = "Pasha";

if (in_array($find_person, $class)) # function returns TRUE or FALSE{

print "$find_person is enrolled. \n";}else{

print "$find_person is not enrolled. \n";}

PHP

Pasha is not enrolled.

OUTPUT

More on strings27

Processing strings

The vast majority of content we will manipulate in

web programming is text. Text is best represented

using string types.

Text is often organized (or semi-organized) into

some type of structure, e.g.

Class list

Name | email address | studentID

Name | email address | studentID

Name | email address | studentID

28

More on strings (and arrays)29

Now that we know how to use arrays, we can

revisit string functions

There are many functions to process strings that

return arrays of strings are their result, or that

take arrays as their parameters

We will examine two very useful string

functions: implode and explode

Functions explode and implode30

Name What does it do?

explode(delim, s)

Takes a string, s, and breaks it

up into multiple strings based

on the delimiter, delim. The

result is an array of string.

implode(delim, a)

Takes an array of strings, a,

and places them back into a

single string separated by the

delimiter, delim.

EECS 1012

What is a delimiter?31

A sequence of one or more symbols

used to specify the boundary

between independent regions.

You use delimiters all the time!

If you didn't add a space delimiter,

text would be unreadable!

https://en.wikipedia.org/wiki/Delimiter

Explode - example32

# imagine we read this string this from a file $bigString = "Abdel | [email protected] | 1238203 \n" .

"Lili | [email protected] | 123888 \n" ."George| [email protected] | 304304 \n" . "Xiong | [email protected] | 111000 ";

print $bigString;

$eachLine = explode("\n", $bigString); # this is an array$numberOfLines = count($eachLine); # this is the size

# the array "eachLine"

print "Number of students = $numberOfLines \n";

PHP

Number of students = 4 outputEECS 1012

Explode – breakdown33

$eachLine = explode("\n", $bigString);

$bigString = "Abdel | [email protected] | 1238203 \n" ."Lili | [email protected] | 123888 \n" ."George| [email protected] | 304304 \n" . "Xiong | [email protected] | 111000";

The string

that we want

to explode.

The delimiter that specifies the

boundaries of what want to separate.

EECS 1012

What is the result?

Explode returns an array that contains the strings

that have been separated by the delimiter.

34

Array

(

[0] => Abdel | [email protected] | 1238203

[1] => Lili | [email protected] | 123888

[2] => George| [email protected] | 304304

[3] => Xiong | [email protected] | 111000

)

$eachLine = explode("\n", $bigString);print_r($eachLine)

Going further35

# imagine we read this string this from a file $bigString = "Abdel | [email protected] | 1238203 \n" .

"Lili | [email protected] | 123888 \n" ."George| [email protected] | 304304 \n" . "Xiong | [email protected] | 111000 ";

$eachLine = explode("\n", $bigString); # this is an array

for ($i = 0; $i < count($eachLine); $i++) {

$info = explode( "|", $eachLine[$i]);print_r($info);

}PHP

Going further36

Array

(

[0] => Abdel | [email protected] | 1238203

[1] => Lili | [email protected] | 123888

[2] => George| [email protected] | 304304

[3] => Xiong | [email protected] | 111000

)

Array

(

[0] => Abdel

[1] => [email protected]

[2] => 1238203

)

Array

(

[0] => Lili

[1] => [email protected]

[2] => 123888

)

Array

(

[0] => George

[1] => [email protected]

[2] => 304304

)

Array

(

[0] => Xiong

[1] => [email protected]

[2] => 111000

)

$eachLine = explode("\n", $bigString);

for ($i = 0; $i < count($eachLine); $i++) {$info = explode( "|", $eachLine[$i]);print_r($info);

}

With two applications of "explode" functions, we have

taken our original string and broke it first into lines,

then each line into the basic "info".

$info[0] is the name

$info[1] is the email

$info[2] is the studentID

Yet even further. . . 37

$bigString = "Abdel | [email protected] | 1238203 \n" ."Lili | [email protected] | 123888 \n" ."George| [email protected] | 304304 \n" . "Xiong | [email protected] | 111000 ";

$eachLine = explode("\n", $bigString); # break into lines

print "<table> \n";print "<tr> <th> Name </th> <th> Email </th> <th> Student ID </th> </tr> \n";

for ($i = 0; $i < count($eachLine); $i++) {$info = explode( "|", $eachLine[$i]); # break line into data# print this out to table!print "<tr><td> $info[0] </td> <td> $info[1] </td> <td> $info[2] </td></tr>\n";}

print "</table> \n";

A Table with a few lines of code!38

<table>

<tr> <th> Name </th> <th> Email </th> <th> Student ID </th> </tr>

<tr> <td> Abdel </td> <td> [email protected] </td> <td> 1238203 </td> </tr>

<tr> <td> Lili </td> <td> [email protected] </td> <td> 123888 </td> </tr>

<tr> <td> George </td> <td> [email protected] </td> <td> 304304 </td> </tr>

<tr> <td> Xiong </td> <td> [email protected] </td> <td> 111000 </td> </tr>

</table>

With just a few lines of code, we have created a table from our

original big string!

See example here

Output from previous slide's PHP code. .

Implode function

Takes an array and forms a big string inserting the

specified delimiter

39

$names = array("Abdel", "Xiong", "Tyler", "Mahsa", "Lili","Deaner", "Tony", "Saeed");

$allNames = implode(",", $names);

print '$names is of type ' . gettype($names) . "\n"; print '$allNames is of type ' . gettype($allNames) . "\n";print '$names = '; print_r($names); print '$allNames = '; print_r($allNames);

See code here

Implode – explained40

$allNames = implode(",", $names);

array to implodeMake a single string by concatenating

all the content with this delimiter inserted

between each item.

$names = Array

(

[0] => Abdel

[1] => Xiong

[2] => Tyler

[3] => Mahsa

[4] => Lili

[5] => Deaner

[6] => Tony

[7] => Saeed

)

EECS 1012

Impode example41

$allNames = implode(",", $names); print $allNames;

PHP

Abdel,Xiong,Tyler,Mahsa,Lili,Deaner,Tony,Saeed

Output

This example took our array of names and created a single string with a delimiter

inserted between each item in the array.

Array/string recap

Arrays are useful data types to store a collection of

data using the same variable name

Two types of arrays: indexed and associative

Many string functions return their results as arrays,

or accept arrays as input

42

EECS 1012

PHP File Input/Output43

Files

File are stored on our "hard drives" – the data

remains there even when the computer is turned off.

We can read and write data to files. These files

are generally stored on the web server.

PHP can read this data into the program.

PHP can also write out information to files.

44

EECS 1012

PHP file diagram45

Text

File

Text file that

is on the server.

PHP can access

this file and

incorporate

its contents into the

output. PHP can

also write information

to this file.

EECS 1012

Facebook has a file on all of you!46

Deaner's File

Likes: Poutine, Beer, Smokes, Hockey

Posts: Just Give'r Terry, …, …, …

Friends: Tron, Terry, Ron

Facebook stores all your information, posts, likes, etc in

files that it accesses each time you log in. It also shares

this information with vendors who want to sell you things.

Basic PHP file I/O functions

function name category

file(filename)

Reads the contents from a file with the

name filename into an array of

strings, where each string is a line

from the file.

file_get_contents(filename)Reads the contents from a file with the

name filename into one large string.

file_put_contents(filename, data, mode)

Write content from data to a file with

the name filename, using a particular

writing mode.

file_exists(filename)Checks to see if a file of filename

exists.

47

I/O is computing speak for "Input/Output"There are many types of file functions for PHP, we will learn these two basic functions.

Reading from a file

file("foo.txt")file_get_contents

("foo.txt")

array(

"Hello\n", #0

"how are\n", #1

"you?\n", #2

"\n", #3

"I'm fine\n" #4 )

"Hello\n

how are\n

you?\n

\n

I'm fine\n"

CS

48

file returns lines of a file as an array

file_get_contents returns entire contents of a file as a

string

EECS 1012

Hello

how are

you?

I'm fine

File: foo.txtFile: foo.txt

Example – quotes.txt

Assume I have a file named "quotes.txt" in my

webserver directory (e.g. www folder).

This file has a quote on each line.

49

"If you want to achieve greatness stop asking for permission." --Anonymous

"Things work out best for those who make the best of how things work out." --John Wooden

"To live a creative life, we must lose our fear of being wrong." –Anonymous

quotes.txt

EECS 1012

Reading a file using file()50

# opens the file and reads content in – each line is placed into an # array $quotes = file("quotes.txt");

# randomly select an index in this array$i = array_rand($quotes);

# convert the $quotes[$i] to special characters # (e.g. " becomes &quot;)$output = htmlspecialchars($quotes[$i]);

print "<p> <quote> $output </quote> </p> \n";

<p> <quote> &quot;Successful entrepreneurs are givers and not takers of positive

energy.&quot; --Anonymous

</quote> </p> OUTPUT

EECS 1012

Reading using file_get_content()51

# opens the file and reads content in as one big string$content = file_get_content("quotes.txt");

# convert the string to all upper case$content = strtoupper ( $content );

# print the strintprint $content;

"IF YOU WANT TO ACHIEVE GREATNESS STOP ASKING FOR PERMISSION." --ANONYMOUS

"THINGS WORK OUT BEST FOR THOSE WHO MAKE THE BEST OF HOW THINGS WORK

OUT." --JOHN WOODEN

"TO LIVE A CREATIVE LIFE, WE MUST LOSE OUR FEAR OF BEING WRONG." --ANONYMOUS

"IF YOU ARE NOT WILLING TO RISK THE USUAL YOU WILL HAVE TO SETTLE FOR THE

ORDINARY." --JIM ROHN

…. OUTPUT

Writing to a file52

for($i=0; $i < 10; $i++){$square = $i * $i;$output[] = "$i * $i = $square \n"; # appends to array

}

# writes an array of strings to the file.file_put_contents("square_table.txt", $output);

0 * 0 = 0

1 * 1 = 1

2 * 2 = 4

3 * 3 = 9

4 * 4 = 16

5 * 5 = 25

6 * 6 = 36

7 * 7 = 49

8 * 8 = 64

9 * 9 = 81

If the file doesn't already

exisit, this creates a file

named "square_table.txt"

and places the following

content in it. If the file did

already exist, this overrides

the content in the file. So,

be careful with file writing!

File: square_table.txt

EECS 1012

Appending to a file (FILE_APPEND)53

for($i=0; $i < 10; $i++){$square = $i * $i;$output[] = "$i * $i = $square \n"; # appends to array

}

file_put_contents("square_table.txt", $output, FILE_APPEND);

If the file already exists, this writes

the data to the end of the file. If the

file doesn't exist, it creates a new file.

….

0 * 0 = 0 (Added to

1 * 1 = 1 the end of

2 * 2 = 4 the existing

3 * 3 = 9 file)

4 * 4 = 16

5 * 5 = 25

6 * 6 = 36

.

File: square_table.txtWhen the FILE_APPEND parameter

is passed to file_put_contents, new

content will be appended to the

end of the file.

EECS 1012

Recap

Basic File I/O is very easy in PHP

File content can be easily read in as an array or a

string

Data can be easily written out to files.

NEXT UP: getting information from HTML files

through forms

54

EECS 1012