Arrays in PHP

784 views
724 views

Published on

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.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
784
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
7
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Arrays in PHP

  1. 1. Use Arrays to Get a Raise By David Haskins
  2. 2. 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.
  3. 3. Data typesA data type is a set of data (information) withcertain characteristics.PHP has: • Booleans • Integers • Floating point numbers • Strings • Arrays • Objects
  4. 4. Data typesA data type is a set of data (information) withcertain characteristics.PHP has: Primitive data types • Booleans (true,false) • Integers • Floating point numbers • Strings • Arrays • Objects
  5. 5. Data typesA data type is a set of data (information) withcertain characteristics.PHP has: Primitive data types • Booleans (true,false) • Integers (…-2,-1,0,1,2,3,4,5…) • Floating point numbers • Strings • Arrays • Objects
  6. 6. Data typesA data type is a set of data (information) withcertain 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
  7. 7. Data typesA data type is a set of data (information) withcertain characteristics.PHP has: Primitive data types & Composite datatypes • 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
  8. 8. Data typesA data type is a set of data (information) withcertain characteristics.PHP has: Primitive data types & Composite datatypes • 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
  9. 9. Data typesA data type is a set of data (information) withcertain characteristics.PHP has: Primitive data types & Composite datatypes • 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…)
  10. 10. What is an array?A data structure in which similar elements ofdata are arranged in a table. - http://www.merriam-webster.com/dictionary/arrayAn ordered collections of items, calledelements. - Zend PHP 5 Certification Study GuideAn ordered map. A map is a type thatassociates values to keys. - http://us2.php.net/manual/en/languages.types.array.php
  11. 11. How do you create an array?//create an empty array$cool_guys = new array();
  12. 12. How do you create an array?//create a populated array$cool_guys = array( Alan Turing, Donald Knuth, Rasmus Lerdorf, John Von Neumann);
  13. 13. 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];
  14. 14. 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 VonNeumann);
  15. 15. How do you create an array?//echo Donald Knuth$cool_guys = array( computers => Alan Turing, algorithms => Donald Knuth, PHP => Rasmus Lerdorf, architecture => John VonNeumann);echo $cool_guys[algorithms];
  16. 16. Add an element to an array?An enumerative array: $cool_guys[] = David Haskins; -or- array_push($cool_guys,David Haskins);
  17. 17. 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 its a function call;however you can add many elements at onceseparated by commas)
  18. 18. Add an element to an array?An associative array: $cool_guys[Memphis] = David Haskins;
  19. 19. Update an existing elementReplace Knuth with DijkstraEnumerative array: $cool_guys[1] = Edsger Dijkstra;Associative array: $cool_guys[algorithms] = Edsger Dijkstra;
  20. 20. Remove an existing elementEnumerative array: unset($cool_guys[1]);Associative array: unset($cool_guys[algorithms]);
  21. 21. Check if an element existsEnumerative array: isset($cool_guys[1]);Associative array: isset($cool_guys[algorithms]);
  22. 22. View the contents of an array//lets look at the enumerative arrayvar_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 }
  23. 23. View the contents of an array//lets look at the enumerative arrayprint_r($cool_guys); Array ( [0] => Alan Turing [1] => Donald Knuth [2] => Rasmus Lerdorf [3] => John Von Neumann )
  24. 24. Multi-dimensional ArraysWhat is a multi-dimensional array?
  25. 25. Multi-dimensional ArraysWhat is a multi-dimensional array?A 2-dimensional array is an array thatcontains another array.
  26. 26. 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), );
  27. 27. Array( [0] => Array print_r($cool_guys); ( [user] => Alan Turing [specialty] => computer [user_id] => 1 ) [1] => Array ( [user] => Donald Knuth [specialty] => algorithms [user_id] => 2 )…snip….)
  28. 28. array(3) { [0]=> var_dump($cool_guys); 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…….}
  29. 29. Let us assume the following enumerativearray:$cool_guys = array( Alan Turing, Donald Knuth, Rasmus Lerdorf, John Von Neumann);
  30. 30. Number of elements in an array$qty = count($cool_guys); // $qty is 4
  31. 31. Iterate over elements in an arrayfor( $i = 0; $i< count($cool_guys); $i++){ //each cool guy echo $cool_guys[$i] . ,;}
  32. 32. Iterate over elements in an arrayfor( $i = 0; $i< count($cool_guys); $i++){ //each cool guy echo $cool_guys[$i] . ,;}Outputs:Alan Turing, Donald Knuth, Rasmus Lerdorf,John Von Neumann,
  33. 33. Iterate over elements in an arrayfor( $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 andrtrim the trailing comma.
  34. 34. Let us assume the following associative array:$cool_guys = array( computers => Alan Turing, algorithms => Donald Knuth, PHP => Rasmus Lerdorf, architectures => John Von Neumann);
  35. 35. Iterate over elements in an arrayforeach($cool_guys as $expertise =>$name){ //each cool guy echo $name is good at $expertise. n ;}
  36. 36. Iterate over elements in an arrayforeach($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.
  37. 37. 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 inthe array, foreach() will not reflect thischange in the iteration.
  38. 38. ExampleCreate a survey in PHP.Just a form that submits information that isstored in a database.Ignore sanitization for simplicity.
  39. 39. Example 1Create two files: • an HTML form • a PHP file to handle form submission(see example 1)
  40. 40. Example 2Add more fields…and there may be evenmore fields to be added at the last minute.
  41. 41. Example 2Add more fields…and there may be evenmore fields to be added at the last minute.Theres one problem…
  42. 42. Example 2Add more fields…and there may be evenmore fields to be added at the last minute.Theres one problem…Doing repetitive stuff is boring.
  43. 43. Example 2Lets use arrays to make life easier.The three chief virtues of a programmer are:laziness, impatience and hubris - Larry Wall (creator of Perl)
  44. 44. Example 2$_POST is an array.Lets take a look at that array.
  45. 45. Example 2print_r($_POST); //placed in submit_form.phpArray ( [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)
  46. 46. Example 3Optional, but I like to do it on tiny projectslike this.Put all code in one file.(check if submitted, and submit to self)
  47. 47. Other things to do with arrays in PHPCant remember what order parameters goin? my_function($user_id,$firm_id,$idx_id);
  48. 48. Other neat things to do with arrays in PHPCant remember what order parameters goin? my_function($user_id,$firm_id,$idx_id);Pass an array: my_function($details);
  49. 49. Other neat things to do with arrays in PHPCant remember what order parameters goin? my_function($user_id,$firm_id,$idx_id);Pass an array: my_function($details);…and use type hinting to only accept anarray: my_function(Array $details);
  50. 50. Not sure what pre-defined Server variables are available? (IIS 7, Im looking at you)print_r($_SERVER);
  51. 51. Not sure what pre-defined Server variables are available? (IIS 7, Im looking at you)print_r($_SERVER);also handy if you cant remember:$_SERVER[PHP_SELF] vs$_SERVER[SCRIPT_NAME] vs$_SERVER[SCRIPT_FILENAME] vs$_SERVER[URL]…etc.
  52. 52. 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] . -;}
  53. 53. 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-!-
  54. 54. explode()$product_info = 2012-06-28-314159;$details = explode(-,$product_info);print_r($details);
  55. 55. explode()$product_info = 2012-06-28-314159;$details = explode(-,$product_info);print_r($details);Array ( [0] => 2012 [1] => 06 [2] => 28 [3] => 314159 )
  56. 56. implode()$my_array = array(a,b,c);$my_str = implode(_,$my_array);echo $my_str;a_b_c
  57. 57. Randomize elements of an arrayshuffle($cards);
  58. 58. Use arraysHopefully, you will be able to use arrays tomanage data in your applications moreefficiently.Look into all of the array functions onPHP.net. There are lots of array sorting,merging, summation, etc. functionsavailable.
  59. 59. Other info on Arrays in PHP• http://oreilly.com/catalog/progphp/chapter/ ch05.html (free chapter!)• Zend PHP 5 Certification Study Guide

×