SlideShare a Scribd company logo
1 of 59
Use Arrays to Get a Raise

     By David Haskins
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.
Data types
A data type is a set of data (information) with
certain characteristics.

PHP has:
     •   Booleans
     •   Integers
     •   Floating point numbers
     •   Strings
     •   Arrays
     •   Objects
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
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
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
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
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
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…)
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
How do you create an array?
//create an empty array
$cool_guys = new array();
How do you create an array?
//create a populated array
$cool_guys = array(
               'Alan Turing',
               'Donald Knuth',
               'Rasmus Lerdorf',
               'John Von Neumann');
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];
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');
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'];
Add an element to an array?
An enumerative array:

    $cool_guys[] = 'David Haskins';
    -or-
    array_push($cool_guys,'David Haskins');
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)
Add an element to an array?
An associative array:

     $cool_guys['Memphis'] = 'David Haskins';
Update an existing element
Replace Knuth with Dijkstra

Enumerative array:
     $cool_guys[1] = 'Edsger Dijkstra';


Associative array:
     $cool_guys['algorithms'] = 'Edsger Dijkstra';
Remove an existing element
Enumerative array:
    unset($cool_guys[1]);

Associative array:
     unset($cool_guys['algorithms']);
Check if an element exists
Enumerative array:
    isset($cool_guys[1]);

Associative array:
     isset($cool_guys['algorithms']);
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'
      }
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
  )
Multi-dimensional Arrays
What is a multi-dimensional array?
Multi-dimensional Arrays
What is a multi-dimensional array?

A 2-dimensional array is an array that
contains another array.
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),
                );
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….
)
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…….
}
Let us assume the following enumerative
array:

$cool_guys = array(
              'Alan Turing',
              'Donald Knuth',
              'Rasmus Lerdorf',
              'John Von Neumann');
Number of elements in an array
$qty = count($cool_guys); // $qty is 4
Iterate over elements in an array
for( $i = 0; $i< count($cool_guys); $i++){
      //each cool guy
      echo $cool_guys[$i] . ',';
}
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,
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.
Let us assume the following associative array:

$cool_guys = array(
     'computers' => 'Alan Turing',
     'algorithms' => 'Donald Knuth',
     'PHP'           => 'Rasmus Lerdorf',
     'architectures' => 'John Von Neumann');
Iterate over elements in an array
foreach($cool_guys as $expertise =>
$name){
     //each cool guy
     echo '$name is good at $expertise. n ';
}
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.
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.
Example
Create a survey in PHP.

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

Ignore sanitization for simplicity.
Example 1
Create two files:
    • an HTML form
    • a PHP file to handle form submission

(see example 1)
Example 2
Add more fields…and there may be even
more fields to be added at the last minute.
Example 2
Add more fields…and there may be even
more fields to be added at the last minute.

There's one problem…
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.
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)
Example 2
$_POST is an array.

Let's take a look at that array.
Example 2
print_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
)
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)
Other things to do with arrays in
                PHP
Can't remember what order parameters go
in?
     my_function($user_id,$firm_id,$idx_id);
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);
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);
Not sure what pre-defined Server
      variables are available?
          (IIS 7, I'm looking at you)



print_r($_SERVER);
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.
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] . '-';
}
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-!-
explode()
$product_info = '2012-06-28-314159';
$details = explode('-',$product_info);
print_r($details);
explode()
$product_info = '2012-06-28-314159';
$details = explode('-',$product_info);
print_r($details);
Array ( [0] => 2012
        [1] => 06
        [2] => 28
         [3] => 314159 )
implode()
$my_array = array('a','b','c');

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

echo $my_str;

a_b_c
Randomize elements of an array
shuffle($cards);
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.
Other info on Arrays in PHP
• http://oreilly.com/catalog/progphp/chapter/
  ch05.html (free chapter!)
• Zend PHP 5 Certification Study Guide

More Related Content

What's hot

PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
 
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, ItalyPHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, ItalyPatrick Allaert
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?Nikita Popov
 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a PythonistRaji Engg
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리용 최
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of AtrocityMichael Pirnat
 
Chap 3php array part 2
Chap 3php array part 2Chap 3php array part 2
Chap 3php array part 2monikadeshmane
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, futuredelimitry
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arraysKumar
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovyIsuru Samaraweera
 
Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 
Banishing Loops with Functional Programming in PHP
Banishing Loops with Functional Programming in PHPBanishing Loops with Functional Programming in PHP
Banishing Loops with Functional Programming in PHPDavid Hayes
 

What's hot (20)

PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)
 
Python Day1
Python Day1Python Day1
Python Day1
 
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, ItalyPHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
 
360|iDev
360|iDev360|iDev
360|iDev
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?
 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a Pythonist
 
Codeware
CodewareCodeware
Codeware
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
 
Chap 3php array part 2
Chap 3php array part 2Chap 3php array part 2
Chap 3php array part 2
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, future
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovy
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
Banishing Loops with Functional Programming in PHP
Banishing Loops with Functional Programming in PHPBanishing Loops with Functional Programming in PHP
Banishing Loops with Functional Programming in PHP
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
 

Viewers also liked

Viewers also liked (16)

Propunere Samfest Jazz / Rock 2013
Propunere Samfest Jazz / Rock 2013Propunere Samfest Jazz / Rock 2013
Propunere Samfest Jazz / Rock 2013
 
Quatorze juillet
Quatorze juilletQuatorze juillet
Quatorze juillet
 
Togaf v9-m3-intro-adm
Togaf v9-m3-intro-admTogaf v9-m3-intro-adm
Togaf v9-m3-intro-adm
 
Eukaryotic cell
Eukaryotic cellEukaryotic cell
Eukaryotic cell
 
Beadványunk a közlekedési rendőrséghez / Sesizare catre Politia Rutiera
Beadványunk a közlekedési rendőrséghez / Sesizare catre Politia RutieraBeadványunk a közlekedési rendőrséghez / Sesizare catre Politia Rutiera
Beadványunk a közlekedési rendőrséghez / Sesizare catre Politia Rutiera
 
Web security
Web securityWeb security
Web security
 
Unit testing
Unit testingUnit testing
Unit testing
 
Togaf v9-m2-togaf9-components
Togaf v9-m2-togaf9-componentsTogaf v9-m2-togaf9-components
Togaf v9-m2-togaf9-components
 
Retrato epsejo dle hombre
Retrato epsejo dle hombreRetrato epsejo dle hombre
Retrato epsejo dle hombre
 
Quatorze juillet
Quatorze juilletQuatorze juillet
Quatorze juillet
 
Agile development
Agile developmentAgile development
Agile development
 
Scan
ScanScan
Scan
 
Togaf v9-m1-management-overview
Togaf v9-m1-management-overviewTogaf v9-m1-management-overview
Togaf v9-m1-management-overview
 
UML and You
UML and YouUML and You
UML and You
 
Nebylitsi
NebylitsiNebylitsi
Nebylitsi
 
Indian Financial System (IFS)
Indian Financial System (IFS)Indian Financial System (IFS)
Indian Financial System (IFS)
 

Similar to Arrays in PHP

Morel, a Functional Query Language
Morel, a Functional Query LanguageMorel, a Functional Query Language
Morel, a Functional Query LanguageJulian Hyde
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptxNawalKishore38
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressAlena Holligan
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An AnalysisJustin Finkelstein
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)monikadeshmane
 
React.js Basics - ConvergeSE 2015
React.js Basics - ConvergeSE 2015React.js Basics - ConvergeSE 2015
React.js Basics - ConvergeSE 2015Robert Pearce
 
python-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptxpython-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptxAkashgupta517936
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docSrikrishnaVundavalli
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesAndrew Ferlitsch
 
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...HendraPurnama31
 
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docximport os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docxBlake0FxCampbelld
 
Rocky Nevin's presentation at eComm 2008
Rocky Nevin's presentation at eComm 2008Rocky Nevin's presentation at eComm 2008
Rocky Nevin's presentation at eComm 2008eComm2008
 
Morel, a data-parallel programming language
Morel, a data-parallel programming languageMorel, a data-parallel programming language
Morel, a data-parallel programming languageJulian Hyde
 

Similar to Arrays in PHP (20)

Morel, a Functional Query Language
Morel, a Functional Query LanguageMorel, a Functional Query Language
Morel, a Functional Query Language
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An Analysis
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
 
React.js Basics - ConvergeSE 2015
React.js Basics - ConvergeSE 2015React.js Basics - ConvergeSE 2015
React.js Basics - ConvergeSE 2015
 
python-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptxpython-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptx
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Decision Tree.pptx
Decision Tree.pptxDecision Tree.pptx
Decision Tree.pptx
 
CSC PPT 13.pptx
CSC PPT 13.pptxCSC PPT 13.pptx
CSC PPT 13.pptx
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...
 
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docximport os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
 
Rocky Nevin's presentation at eComm 2008
Rocky Nevin's presentation at eComm 2008Rocky Nevin's presentation at eComm 2008
Rocky Nevin's presentation at eComm 2008
 
Morel, a data-parallel programming language
Morel, a data-parallel programming languageMorel, a data-parallel programming language
Morel, a data-parallel programming language
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

Arrays in PHP

  • 1. Use Arrays to Get a Raise By David Haskins
  • 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. Data types A data type is a set of data (information) with certain characteristics. PHP has: • Booleans • Integers • Floating point numbers • Strings • Arrays • Objects
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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…)
  • 10. 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
  • 11. How do you create an array? //create an empty array $cool_guys = new array();
  • 12. How do you create an array? //create a populated array $cool_guys = array( 'Alan Turing', 'Donald Knuth', 'Rasmus Lerdorf', 'John Von Neumann');
  • 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. 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');
  • 15. 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'];
  • 16. Add an element to an array? An enumerative array: $cool_guys[] = 'David Haskins'; -or- array_push($cool_guys,'David Haskins');
  • 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 it's a function call; however you can add many elements at once separated by commas)
  • 18. Add an element to an array? An associative array: $cool_guys['Memphis'] = 'David Haskins';
  • 19. Update an existing element Replace Knuth with Dijkstra Enumerative array: $cool_guys[1] = 'Edsger Dijkstra'; Associative array: $cool_guys['algorithms'] = 'Edsger Dijkstra';
  • 20. Remove an existing element Enumerative array: unset($cool_guys[1]); Associative array: unset($cool_guys['algorithms']);
  • 21. Check if an element exists Enumerative array: isset($cool_guys[1]); Associative array: isset($cool_guys['algorithms']);
  • 22. 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' }
  • 23. 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 )
  • 24. Multi-dimensional Arrays What is a multi-dimensional array?
  • 25. Multi-dimensional Arrays What is a multi-dimensional array? A 2-dimensional array is an array that contains another array.
  • 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. 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. 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. Let us assume the following enumerative array: $cool_guys = array( 'Alan Turing', 'Donald Knuth', 'Rasmus Lerdorf', 'John Von Neumann');
  • 30. Number of elements in an array $qty = count($cool_guys); // $qty is 4
  • 31. Iterate over elements in an array for( $i = 0; $i< count($cool_guys); $i++){ //each cool guy echo $cool_guys[$i] . ','; }
  • 32. 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,
  • 33. 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.
  • 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. Iterate over elements in an array foreach($cool_guys as $expertise => $name){ //each cool guy echo '$name is good at $expertise. n '; }
  • 36. 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.
  • 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 in the array, foreach() will not reflect this change in the iteration.
  • 38. Example Create a survey in PHP. Just a form that submits information that is stored in a database. Ignore sanitization for simplicity.
  • 39. Example 1 Create two files: • an HTML form • a PHP file to handle form submission (see example 1)
  • 40. Example 2 Add more fields…and there may be even more fields to be added at the last minute.
  • 41. Example 2 Add more fields…and there may be even more fields to be added at the last minute. There's one problem…
  • 42. 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.
  • 43. 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)
  • 44. Example 2 $_POST is an array. Let's take a look at that array.
  • 45. Example 2 print_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 )
  • 46. 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)
  • 47. Other things to do with arrays in PHP Can't remember what order parameters go in? my_function($user_id,$firm_id,$idx_id);
  • 48. 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);
  • 49. 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);
  • 50. Not sure what pre-defined Server variables are available? (IIS 7, I'm looking at you) print_r($_SERVER);
  • 51. 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.
  • 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. 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. explode() $product_info = '2012-06-28-314159'; $details = explode('-',$product_info); print_r($details);
  • 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. implode() $my_array = array('a','b','c'); $my_str = implode('_',$my_array); echo $my_str; a_b_c
  • 57. Randomize elements of an array shuffle($cards);
  • 58. 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.
  • 59. Other info on Arrays in PHP • http://oreilly.com/catalog/progphp/chapter/ ch05.html (free chapter!) • Zend PHP 5 Certification Study Guide