PHP Arrays
Dr. Charles Severance
www.wa4e.com
http://www.wa4e.com/code/arrays
http://www.wa4e.com/code/arrays.zip
PHP Arrays Rock!
• Better than Python Dictionaries
• Better than Java Hash Maps
• PHP Arrays have all the benefits of Python Dictionaries but
they can also maintain the order of the items in the array
http://en.wikipedia.org/wiki/Associative_array
Associative Arrays
Can be key => value or simply indexed by numbers
Ignore two-dimensional arrays for now...
http://en.wikipedia.org/wiki/Associative_array
Integer Indices
<?php
$stuff = array("Hi", "There");
echo $stuff[1], "\n";
?>
There
Key / Value
<?php
$stuff = array("name" => "Chuck",
"course" => "WA4E");
echo $stuff["course"], "\n";
?>
WA4E
Dumping an Array
The function print_r() shows PHP data - it is good for debugging.
<?php
$stuff = array("name" => "Chuck",
"course" => "WA4E");
echo("<pre>\n");
print_r($something);
echo("\n</pre>\n"); Array(
?> [name] => Chuck
[course] => WA4E
)
var_dump vs. print_r
<?php
$stuff = array("name" => "Chuck",
"course" => "SI664");
var_dump($stuff);
?>
array(2) {
["name"]=>
string(5) "Chuck"
["course"]=>
string(5) "SI664"
}
var_dump() and false
<?php
$thing = FALSE;
echo("One\n");
print_r($thing);
echo("Two\n"); One
var_dump($thing); Two
?> bool(false)
http://stackoverflow.com/questions/3406171/php-var-dump-vs-print-r
Building Up an Array
You can allocate a new item in the array and append a value
at the same time using empty square braces [ ] on the right
hand side of an assignment statement.
$va = array(); Array(
$va[] = "Hello"; [0] => Hello
$va[] = "World"; [1] => World
print_r($va); )
Building Up an Array
You can also add new items in an array using a key.
$za = array(); Array(
$za["name"] = "Chuck"; [name] => Chuck
$za["course"] = "WA4E"; [course] => WA4E
print_r($za); )
Looping Through an Array
<?php
$stuff = array("name" => "Chuck",
"course" => "SI664");
foreach($stuff as $k => $v ) {
echo "Key=",$k," Val=",$v,"\n";
}
?>
Key=name Val=Chuck
Key=course Val=SI664
Looping Through an Array
<?php
$stuff = array("Chuck","SI664");
foreach($stuff as $k => $v ) {
echo "Key=",$k," Val=",$v,"\n";
}
?>
Key=0 Val=Chuck
Key=1 Val=SI664
Counted Loop Through an Array
<?php
$stuff = array("Chuck","SI664");
for($i=0; $i < count($stuff); $i++) {
echo "I=",$i," Val=",$stuff[$i],"\n";
}
?>
I=0 Val=Chuck
I=1 Val=SI664
Arrays of $products = array(
'paper' => array(
'copier' => "Copier & Multipurpose",
Arrays 'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper"),
'pens' => array(
The elements of an array 'ball' => "Ball Point",
'hilite' => "Highlighters",
can be many things other 'marker' => "Markers"),
than a string or integer. 'misc' => array(
'tape' => "Sticky Tape",
You can even have objects 'glue' => "Adhesives",
or other arrays. 'clips' => "Paperclips")
);
echo $products["pens"]["marker"];
Markers
Array Functions
Array Functions
array_key_exists($key, $ar) - Returns TRUE if key is set in the array
isset($ar['key']) - Returns TRUE if key is set in the array
count($ar) - How many elements in an array
is_array($ar) - Returns TRUE if a variable is an array
sort($ar) - Sorts the array values (loses key)
ksort($ar) - Sorts the array by key
asort($ar) - Sorts array by value, keeping key association
shuffle($ar) - Shuffles the array into random order
$za = array();
Course exists
$za["name"] = "Chuck"; name is set
$za["course"] = "WA4E"; addr is not set
if (array_key_exists('course',$za) ) {
echo("Course exists\n");
} else {
echo("Course does not exist\n");
}
echo isset($za['name']) ? "name is set\n" : "name is not set\n";
echo isset($za['addr']) ? "addr is set\n" : "addr is not set\n";
<?php
$za = array(); Null
$za["name"] = "Chuck";
$za["course"] = "WA4E"; Coalesce
// PHP >= 7.0.0 only
$name = $za['name'] ?? 'not found';
$addr = $za['addr'] ?? 'not found'; Name=Chuck
Addr=not found
echo("Name=$name\n");
echo("Addr=$addr\n");
// PHP < 7.0.0 equivalent
$name = isset($za['name']) ? $za['name'] : 'not found';
$za = array(); Count: 2
$za["name"] = "Chuck"; $za Is an array
$za["course"] = "WA4E";
print "Count: " . count($za) . "\n";
if ( is_array($za) ) {
echo '$za Is an array' . "\n";
} else {
echo '$za Is not an array' . "\n";
}
Array(
$za = array(); [name] => Chuck
$za["name"] = "Chuck"; [course] => WA4E
$za["course"] = "WA4E"; [topic] => PHP
$za["topic"] = "PHP"; )
print_r($za); Array(
sort($za); [0] => Chuck
print_r($za); [1] => PHP
[2] => WA4E
)
Array(
[name] => Chuck
$za = array(); [course] => WA4E
$za["name"] = "Chuck"; [topic] => PHP
$za["course"] = "WA4E"; )
$za["topic"] = "PHP";
Array(
print_r($za); [course] => WA4E
ksort($za); [name] => Chuck
print_r($za); [topic] => PHP
asort($za); )
print_r($za);
Array(
[name] => Chuck
[topic] => PHP
[course] => WA4E
)
Exploding Arrays
$inp = "This is a sentence with seven words";
$temp = explode(' ', $inp);
print_r($temp);
Array(
[0] => This
[1] => is
[2] => a
[3] => sentence
[4] => with
[5] => seven
[6] => words
)
Arrays and URL Parameters
Time Browser Web Server Database Server
D
Apache
O static MySql
Parse
M Request
files
Parse
Response $_GET
PHP php
code
ind.php
JavaScrip
t
RRC/HTTP SQL
http://www.wa4e.com/code/arrays/get-01.php?x=2&y=4
Summary
This is a sprint through some of the unique
language features of PHP Arrays.
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance Continue new Contributors and Translators here
(www.dr-chuck.com) as part of www.wa4e.com and made
available under a Creative Commons Attribution 4.0 License.
Please maintain this last slide in all copies of the document to
comply with the attribution requirements of the license. If you
make a change, feel free to add your name and organization
to the list of contributors on this page as you republish the
materials.
Initial Development: Charles Severance, University of
Michigan School of Information
Insert new Contributors and Translators here including names
and dates