Arrays in PHP

59
Use Arrays to Get a Raise By David Haskins

description

A presentation I gave at Memphis PHP Meetup June 28, 2012. Feel free to use it as you like, but please give credit to me (David Haskins). You may want to remove the Example slides - I haven't uploaded the PHP files.

Transcript of Arrays in PHP

Page 1: Arrays in PHP

Use Arrays to Get a Raise

By David Haskins

Page 2: Arrays in PHP

Use Arrays to Get a Raise*

By David Haskins

*No raise guaranteed or implied. Raises are subject to availability. Contact your supervisor for details. Offer not valid where prohibited.

Page 3: Arrays in PHP

Data types

A data type is a set of data (information) with certain characteristics.

PHP has:• Booleans • Integers• Floating point numbers• Strings• Arrays• Objects

Page 4: Arrays in PHP

Data types

A data type is a set of data (information) with certain characteristics.

PHP has: Primitive data types• Booleans (true,false)• Integers • Floating point numbers• Strings• Arrays • Objects

Page 5: Arrays in PHP

Data types

A data type is a set of data (information) with certain characteristics.

PHP has: Primitive data types• Booleans (true,false)• Integers (…-2,-1,0,1,2,3,4,5…)• Floating point numbers • Strings• Arrays • Objects

Page 6: Arrays in PHP

Data types

A data type is a set of data (information) with certain characteristics.

PHP has: Primitive data types• Booleans (true,false)• Integers (…-2,-1,0,1,2,3,4,5…)• Floating point numbers (3.14159,2.71828…)• Strings • Arrays• Objects

Page 7: Arrays in PHP

Data types

A data type is a set of data (information) with certain characteristics.

PHP has: Primitive data types & Composite data types

• Booleans (true,false)• Integers (…-2,-1,0,1,2,3,4,5…)• Floating point numbers (3.14159,2.71828…)• Strings ('Memphis', 'Meetup Group'…)• Arrays • Objects

Page 8: Arrays in PHP

Data types

A data type is a set of data (information) with certain characteristics.

PHP has: Primitive data types & Composite data types

• Booleans (true,false)• Integers (…-2,-1,0,1,2,3,4,5…)• Floating point numbers (3.14159,2.71828…)• Strings ('Memphis', 'Meetup Group'…)• Arrays ($_SERVER, $user = new array()…)• Objects

Page 9: Arrays in PHP

Data types

A data type is a set of data (information) with certain characteristics.

PHP has: Primitive data types & Composite data types

• Booleans (true,false)• Integers (…-2,-1,0,1,2,3,4,5…)• Floating point numbers (3.14159,2.71828…)• Strings ('Memphis', 'Meetup Group'…)• Arrays ($_SERVER, $user = new array()…)• Objects (user, animal, bird…)

Page 10: Arrays in PHP

What is an array?

A data structure in which similar elements of data are arranged in a table.

- http://www.merriam-webster.com/dictionary/array

An ordered collections of items, called elements. - Zend PHP 5 Certification Study Guide

An ordered map. A map is a type that associates values to keys.

- http://us2.php.net/manual/en/languages.types.array.php

Page 11: Arrays in PHP

How do you create an array?

//create an empty array

$cool_guys = new array();

Page 12: Arrays in PHP

How do you create an array?

//create a populated array

$cool_guys = array(

'Alan Turing',

'Donald Knuth',

'Rasmus Lerdorf',

'John Von Neumann');

Page 13: Arrays in PHP

How do you create an array?

//echo Donald Knuth

$cool_guys = array(

'Alan Turing',

'Donald Knuth',

'Rasmus Lerdorf',

'John Von Neumann');

echo $cool_guys[1];

Page 14: Arrays in PHP

How do you create an array?

//create a populated associative array

$cool_guys = array(

'computers' => 'Alan Turing',

'algorithms' => 'Donald Knuth',

'PHP' => 'Rasmus Lerdorf',

'architecture' => 'John Von Neumann');

Page 15: Arrays in PHP

How do you create an array?

//echo Donald Knuth

$cool_guys = array(

'computers' => 'Alan Turing',

'algorithms' => 'Donald Knuth',

'PHP' => 'Rasmus Lerdorf',

'architecture' => 'John Von Neumann');

echo $cool_guys['algorithms'];

Page 16: Arrays in PHP

Add an element to an array?

An enumerative array:

$cool_guys[] = 'David Haskins';

-or-

array_push($cool_guys,'David Haskins');

Page 17: Arrays in PHP

Add an element to an array?

An enumerative array:

$cool_guys[] = 'Jeremy Kendall';

-or-

array_push($cool_guys,'Jeremy Kendall');

(array_push() is slower b/c it's a function call; however you can add many elements at once separated by commas)

Page 18: Arrays in PHP

Add an element to an array?

An associative array:

$cool_guys['Memphis'] = 'David Haskins';

Page 19: Arrays in PHP

Update an existing element

Replace Knuth with Dijkstra

Enumerative array:

$cool_guys[1] = 'Edsger Dijkstra';

Associative array:$cool_guys['algorithms'] = 'Edsger Dijkstra';

Page 20: Arrays in PHP

Remove an existing element

Enumerative array:

unset($cool_guys[1]);

Associative array:unset($cool_guys['algorithms']);

Page 21: Arrays in PHP

Check if an element exists

Enumerative array:

isset($cool_guys[1]);

Associative array:isset($cool_guys['algorithms']);

Page 22: Arrays in PHP

View the contents of an array

//let's look at the enumerative array

var_dump($cool_guys);

array(4) {

[0]=>

string(11) 'Alan Turing'

[1]=>

string(12) 'Donald Knuth'

[2]=>

string(14) 'Rasmus Lerdorf'

[3]=>

string(16) 'John Von Neumann'

}

Page 23: Arrays in PHP

View the contents of an array

//let's look at the enumerative array

print_r($cool_guys);Array

(

[0] => Alan Turing

[1] => Donald Knuth

[2] => Rasmus Lerdorf

[3] => John Von Neumann

)

Page 24: Arrays in PHP

Multi-dimensional Arrays

What is a multi-dimensional array?

Page 25: Arrays in PHP

Multi-dimensional Arrays

What is a multi-dimensional array?

A 2-dimensional array is an array that contains another array.

Page 26: Arrays in PHP

2-dimensional array

$cool_guys = array( 0 => array(

'user' => 'Alan Turing',

'specialty' => 'computer',

'user_id' => 1000),

1 => array(

'user' => 'Donald Knuth',

'specialty' => 'algorithms',

'user_id' => 1001),

2 => array(

'user' => 'Rasmus Lerdorf',

'specialty' => 'PHP',

'user_id' => 1002),

);

Page 27: Arrays in PHP

print_r($cool_guys);Array

(

[0] => Array

(

[user] => Alan Turing

[specialty] => computer

[user_id] => 1

)

[1] => Array

(

[user] => Donald Knuth

[specialty] => algorithms

[user_id] => 2

)

…snip….

)

Page 28: Arrays in PHP

var_dump($cool_guys);array(3) {

[0]=>

array(3) {

['user']=>

string(11) 'Alan Turing'

['specialty']=>

string(8) 'computer'

['user_id']=>

int(1)

}

[1]=>

array(3) {

['user']=>

string(12) 'Donald Knuth'

['specialty']=>

string(10) 'algorithms'

['user_id']=>

int(2)

}

…….snip…….

}

Page 29: Arrays in PHP

Let us assume the following enumerative array:

$cool_guys = array(

'Alan Turing',

'Donald Knuth',

'Rasmus Lerdorf',

'John Von Neumann');

Page 30: Arrays in PHP

Number of elements in an array

$qty = count($cool_guys); // $qty is 4

Page 31: Arrays in PHP

Iterate over elements in an array

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

//each cool guy

echo $cool_guys[$i] . ',';

}

Page 32: Arrays in PHP

Iterate over elements in an array

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

//each cool guy

echo $cool_guys[$i] . ',';

}

Outputs:

Alan Turing, Donald Knuth, Rasmus Lerdorf, John Von Neumann,

Page 33: Arrays in PHP

Iterate over elements in an array

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

//each cool guy

echo $cool_guys[$i] . ',';

}

Outputs:

Alan Turing, Donald Knuth, Rasmus Lerdorf, John Von Neumann,

Note: you could store the output as a string and rtrim the trailing comma.

Page 34: Arrays in PHP

Let us assume the following associative array:

$cool_guys = array(

'computers' => 'Alan Turing',

'algorithms' => 'Donald Knuth',

'PHP' => 'Rasmus Lerdorf',

'architectures' => 'John Von Neumann');

Page 35: Arrays in PHP

Iterate over elements in an array

foreach($cool_guys as $expertise => $name){

//each cool guy

echo '$name is good at $expertise. \n ';

}

Page 36: Arrays in PHP

Iterate over elements in an array

foreach($good_guys as $expertise => $name){

//each cool guy

echo '$name is good at $expertise. \n ';

}

Alan Turing is good at computers.

Donald Knuth is good at algorithms.

Rasmus Lerdorf is good at PHP.

John Von Neumann is good at architectures.

Page 37: Arrays in PHP

for() vs foreach()

for() and foreach() are not the same thing!

foreach() operates on a copy of the array, not the array itself. If you modify a value in the array, foreach() will not reflect this change in the iteration.

Page 38: Arrays in PHP

Example

Create a survey in PHP.

Just a form that submits information that is stored in a database.

Ignore sanitization for simplicity.

Page 39: Arrays in PHP

Example 1

Create two files:• an HTML form• a PHP file to handle form submission

(see example 1)

Page 40: Arrays in PHP

Example 2

Add more fields…and there may be even more fields to be added at the last minute.

Page 41: Arrays in PHP

Example 2

Add more fields…and there may be even more fields to be added at the last minute.

There's one problem…

Page 42: Arrays in PHP

Example 2

Add more fields…and there may be even more fields to be added at the last minute.

There's one problem…

Doing repetitive stuff is boring.

Page 43: Arrays in PHP

Example 2

Let's use arrays to make life easier.

'The three chief virtues of a programmer are: laziness, impatience and hubris'

- Larry Wall (creator of Perl)

Page 44: Arrays in PHP

Example 2

$_POST is an array.

Let's take a look at that array.

Page 45: Arrays in PHP

Example 2print_r($_POST); //placed in submit_form.php

Array (

[first_name] => David

[last_name] => Haskins

[address_1] => 1099 Legacy Farm Court

[address_2] => Apt 202

[city] => Collierville

[state] => Tennessee (TN)

[zip] => 38017

[like_our_product] => wonderful

[like_our_service] => wonderful

[submit] => submit

)

Page 46: Arrays in PHP

Example 3

Optional, but I like to do it on tiny projects like this.

Put all code in one file.

(check if submitted, and submit to self)

Page 47: Arrays in PHP

Other things to do with arrays in PHP

Can't remember what order parameters go in?

my_function($user_id,$firm_id,$idx_id);

Page 48: Arrays in PHP

Other neat things to do with arrays in PHP

Can't remember what order parameters go in?

my_function($user_id,$firm_id,$idx_id);

Pass an array:

my_function($details);

Page 49: Arrays in PHP

Other neat things to do with arrays in PHP

Can't remember what order parameters go in?

my_function($user_id,$firm_id,$idx_id);

Pass an array:

my_function($details);

…and use type hinting to only accept an array:

my_function(Array $details);

Page 50: Arrays in PHP

Not sure what pre-defined Server variables are available?

(IIS 7, I'm looking at you)

print_r($_SERVER);

Page 51: Arrays in PHP

Not sure what pre-defined Server variables are available?

(IIS 7, I'm looking at you)

print_r($_SERVER);

also handy if you can't remember:$_SERVER['PHP_SELF'] vs $_SERVER['SCRIPT_NAME'] vs

$_SERVER['SCRIPT_FILENAME'] vs

$_SERVER['URL']…etc.

Page 52: Arrays in PHP

Treat a string as an enumerative array of chars

$my_str = 'PHP Memphis rocks!';

for($i=0; $i<strlen($my_str); $i++){

echo $my_str[$i] . '-';

}

Page 53: Arrays in PHP

Treat a string as an enumerative array of chars

$my_str = 'PHP Memphis rocks!';

for($i=0; $i<strlen($my_str); $i++){

echo $my_str[$i] . '-';

}

P-H-P- -M-e-m-p-h-i-s- -r-o-c-k-s-!-

Page 54: Arrays in PHP

explode()

$product_info = '2012-06-28-314159';

$details = explode('-',$product_info);

print_r($details);

Page 55: Arrays in PHP

explode()

$product_info = '2012-06-28-314159';

$details = explode('-',$product_info);

print_r($details);

Array ( [0] => 2012

[1] => 06

[2] => 28

[3] => 314159 )

Page 56: Arrays in PHP

implode()

$my_array = array('a','b','c');

$my_str = implode('_',$my_array);

echo $my_str;

a_b_c

Page 57: Arrays in PHP

Randomize elements of an array

shuffle($cards);

Page 58: Arrays in PHP

Use arrays

Hopefully, you will be able to use arrays to manage data in your applications more efficiently.

Look into all of the array functions on PHP.net. There are lots of array sorting, merging, summation, etc. functions available.

Page 59: Arrays in PHP

Other info on Arrays in PHP

• http://oreilly.com/catalog/progphp/chapter/ch05.html (free chapter!)

• Zend PHP 5 Certification Study Guide