Functions & Arrays
Henry Osborne
PHP Functions & Arrays
Basic Syntax
function name() { }
function hello() {
echo “Hello World!”;
}
hello();
Returning Values
function hello() {
return “Hello World!”;
}
$txt = hello();
echo hello();
Returning Values
function hello() {
echo “Hello $who”;
if ($who == “World”) {
return;

}
echo “, how are you?”;
}
hello (“World”); //Displays “Hello World”

hello (“Reader”); //Displays “Hello Reader, how are you?”
Returning Values
function &query($sql)
{
$result = mysql_query($sql);
return $result;
}
//The following is incorrect and will
cause PHP to emit a notice when called.
function &getHello()
{
return “Hello World”;
}

//This will also cause the warning to be
issued when called
function &test()
{
echo „This is a test‟;
}
Variable Scope
• Three variable scopes exist:
• Global
• Function
• Class
Variable Scope, cont’d
$a = “Hello World”;
function hello() {
$a = “Hello Reader”;
$b = “How are you?”;
}
hello ();
echo $a; //Will output Hello World
echo $b; //Will emit a warning
Variable Scope, cont’d
$a = “Hello”;
$b = “World”;
function hello() {

global $a, $b;
echo “$a $b”;
}

hello (); //Displays Hello World
Variable Scope, cont’d
$a = “Hello”;
$b = “World”;
function hello() {
echo $GLOBALS[„a‟].‟ „.$GLOBALS[„b‟];
}
hello (); //Displays Hello World
Variable-Length Argument Lists
function hello() {
if (func_num_args() > 0) {
$arg = func_get_arg(0);
echo “Hello $arg”;

} else {
echo ”Hello World”;
}
}

hello(“Reader);
Variable-Length Argument Lists
function countAll($arg1){
if (func_num_args() == 0) {
die(“You need to specify at least
one argument”);
} else {
$args = func_get_args();

array_shift($args);
$count = strlen($arg1);
foreach ($args as $arg) {
$count += strlen($arg);
}

}
return $count;
}
echo countAll(“apple”,”pear”, “plum”);
Passing Arguments by Reference
function countAll(&$count){
if (func_num_args() == 0) {
die(“You need to specify at least
one argument”);
} else {
$args = func_get_args();

array_shift($args);
$count = strlen($arg1);
foreach ($args as $arg) {
$count += strlen($arg);
}

}

}
$count = 0;
countAll($count, “apple”,”pear”, “plum”);
//count now equals 13
Arrays
Array Basics
$a = array (10, 20, 30);
$a = array (‟a‟ => 10, ‟b‟ => 20, ‟cee‟ => 30);
$a = array (5 => 1, 3 => 2, 1 => 3,);

$a = array();
Array Basics
$x[] = 10;
$x[‟aa‟] = 11;
echo $x[0]; // Outputs 10
Printing Arrays
• PHP provides two functions that can be used to output a
variable’s value recursively
• print_r()
• var_dump().
Enumerative vs Associative
• Arrays can be roughly divided in two categories: enumerative and
associative.

• Enumerative arrays are indexed using only numerical indexes
• Associative arrays(sometimes referred to as dictionaries) allow the
association of an arbitrary key to every element.
Enumerative vs Associative, cont’d
When an element is added to an array without specifying a key, PHP
automatically assigns a numeric one that is equal to the greatest numeric key
already in existence in the array, plus one:
$a = array (2 => 5);
$a[] = ‟a‟; // This will have a key of 3
$a = array (‟4‟ => 5, ‟a‟ => ‟b‟);
$a[] = 44; // This will have a key of 5
Array keys are case-sensitive, but type insensitive. Thus, the key ’A’
is different from the key ’a’, but the keys ’1’ and 1 are the same.
However, the conversion is only applied if a string key contains
the traditional decimal representation of a number; thus, for
example, the key ’01’ is not the same as the key 1.

NOTE WELL
Multi-dimensional Arrays
$array = array();
$array[] = array(‟foo‟, ‟bar‟);
$array[] = array(‟baz‟, ‟bat‟);

echo $array[0][1] . $array[1][0]; //output is barbaz
Unravelling Arrays
$sql = "SELECT user_first, user_last, lst_log FROM
users";
$result = mysql_query($sql);

while (list($first, $last, $last_login) =
mysql_fetch_row($result)) {
echo "$last, $first - Last Login: $last_login";

}
array(6) {
[0]=>

Array Operations

int(1)
[1]=>
int(2)
[2]=>

$a = array (1, 2, 3);

int(3)

$b = array (‟a‟ => 1, ‟b‟ => 2, ‟c‟ => 3);

["a"]=>

var_dump ($a + $b);

int(1)
["b"]=>

int(2)
["c"]=>
int(3)

}
Array Operations, cont’d

array(4) {
[0]=>
int(1)

$a = array (1, 2, 3);

[1]=>

$b = array (‟a‟ => 1, 2, 3);

int(2)

var_dump ($a + $b);

[2]=>
int(3)
["a"]=>
int(1)

}
Comparing Arrays
$a = array (1, 2, 3);
$b = array (1 => 2, 2 => 3, 0 => 1);
$c = array (‟a‟ => 1, ‟b‟ => 2, ‟c‟ => 3);

var_dump ($a == $b); // True
var_dump ($a === $b); // False
var_dump ($a == $c); // False

var_dump ($a === $c); // False
Comparing Arrays, cont’d
$a = array (1, 2, 3);
$b = array (1 => 2, 2 => 3, 0 => 1);
var_dump ($a != $b); // False
var_dump ($a !== $b); // True
Counting, Searching and Deleting Elements
$a = array (1, 2, 4);
$b = array();
$c = 10;
echo count ($a); // Outputs 3
echo count ($b); // Outputs 0
echo count ($c); // Outputs 1
Counting, Searching and Deleting Elements, cont’d
$a = array (‟a‟ => 1, ‟b‟ => 2);
echo isset ($a[‟a‟]); // True
echo isset ($a[‟c‟]); // False
$a = array (‟a‟ => NULL, ‟b‟ => 2);
echo isset ($a[‟a‟]); // False
Counting, Searching and Deleting Elements, cont’d
$a = array (‟a‟ => NULL, ‟b‟ => 2);
echo array_key_exists (‟a‟, $a); // True
$a = array (‟a‟ => NULL, ‟b‟ => 2);
echo in_array (2, $a); // True
Counting, Searching and Deleting Elements, cont’d
$a = array (‟a‟ => NULL, ‟b‟ => 2);
unset ($a[‟b‟]);
echo in_array ($a, 2); // False
Flipping and Reversing
$a = array (‟a‟, ‟b‟, ‟c‟);

array(3) {{
array(3)
["a"]=>
[0]=>
int(0)
string(1) "c"
["b"]=>
[1]=>
int(1)
string(1) "b"
["c"]=>
["x"]=>
int(2)
string(1) "a"

var_dump (array_flip ($a));

$a = array (‟x‟ => ‟a‟, 10 => ‟b‟, ‟c‟);
var_dump (array_reverse ($a));

}}
Array Iteration
• One of the most common operations you will perform with arrays
• PHP arrays require a set of functionality that matches their flexibility
• “normal” looping structures cannot cope with the fact that array keys do not
need to be continuous
$a = array (‟a‟ => 10, 10 => 20, ‟c‟ => 30);
Array Iteration: Array Pointer
$array = array(‟foo‟ => ‟bar‟, ‟baz‟, ‟bat‟ => 2);
function displayArray(&$array) {
reset($array);
while (key($array) !== null) {
echo key($array) .": " .current($array) . PHP_EOL;
next($array);

}

}
Array Iteration: foreach
$array = array(‟foo‟, ‟bar‟, ‟baz‟);
foreach ($array as $key => $value) {
echo "$key: $value";
}
array(2) {
["internal"]=>

Passive Iteration

&array(3) {
[0]=>
string(3) "RSS"
[1]=>

function setCase(&$value, &$key)

string(4) "HTML"

{

[2]=>
string(3) "XML"

$value = strtoupper($value);

}

}

["custom"]=>

$type = array(‟internal‟, ‟custom‟);

&array(2) {

$output_formats[] = array(‟rss‟, ‟html‟, ‟xml‟);

[0]=>

$output_formats[] = array(‟csv‟, ‟json‟);

string(3) "CSV"

$map = array_combine($type, $output_formats);

[1]=>

array_walk_recursive($map, ‟setCase‟);

string(4) "JSON"

}

var_dump($map);

}
Sorting Arrays: sort()
$array = array(‟a‟ => ‟foo‟, ‟b‟ => ‟bar‟, ‟c‟ => ‟baz‟);
sort($array);

array(3) {
[0]=>

var_dump($array);

string(3) "bar"
[1]=>
string(3) "baz"
[2]=>
string(3) "foo"

}
Sorting Arrays: asort()
$array = array(‟a‟ => ‟foo‟, ‟b‟ => ‟bar‟, ‟c‟ => ‟baz‟);
asort($array);
var_dump($array);

array(3) {
["b"]=>
string(3) "bar"
["c"]=>
string(3) "baz"
["a"]=>
string(3) "foo“
}
Sorting Arrays
SORT_REGULAR

Compare items as they appear in the array, without performing any kind of
conversion. This is the default behaviour.

SORT_NUMERIC

Convert each element to a numeric value for sorting purposes.

SORT_STRING

Compare all elements as strings.
Sorting Arrays: natsort()
$array = array(‟10t‟, ‟2t‟, ‟3t‟);
natsort($array);

array(3) {
[1]=>

var_dump($array);

string(2) "2t"
[2]=>
string(2) "3t"
[0]=>
string(3) "10t"

}
Anti-Sorting: shuffle()
$cards = array (1, 2, 3, 4);

array(4) {
[0]=>

shuffle($cards);

int(4)

var_dump($cards);

[1]=>
int(1)
[2]=>
int(2)
[3]=>

int(3)

}
Anti-Sorting: array_keys()
$cards = array (‟a‟ => 10, ‟b‟ => 12, ‟c‟ => 13);
$keys = array_keys ($cards);
shuffle($keys);
foreach ($keys as $v) {
echo $v . " - " . $cards[$v] . "n";
}
Anti-Sorting: array_rand()
$cards = array (‟a‟ => 10, ‟b‟ => 12, ‟c‟ =>array(2) { {
13);
array(3)
$keys = array_rand ($cards, 2);
["a"]=>
[0]=>
int(10)
string(1) "a"

["b"]=>
[1]=>

var_dump($keys);

int(12)
string(1) "b"

var_dump($cards);

["c"]=>

}

int(13)

}
Arrays as Stacks, Queues and Sets
$stack = array();
array_push($stack, ‟bar‟, ‟baz‟);
var_dump($stack);
$last_in = array_pop($stack);
var_dump($last_in, $stack);
Arrays as Stacks, Queues and Sets
array(2) {
[0]=>

$queue = array(‟qux‟, ‟bar‟, ‟baz‟);

string(3) "bar"
[1]=>

$first_element = array_shift($queue);
var_dump($queue);

string(3) "baz"

}
array(3) {

array_unshift($queue, ‟foo‟);

[0]=>
string(3) "foo"

var_dump($queue);

[1]=>

string(3) "bar"
[2]=>
string(3) "baz"

}
Set Functionality
$a = array (1, 2, 3);
$b = array (1, 3, 4);
var_dump (array_diff ($a, $b));
var_dump (array_intersect ($a, $b));
Functions & Arrays

More Related Content

PPT
SQLITE Android
PPT
PPTX
JavaScript Promises
PPT
Class 3 - PHP Functions
PPTX
Sessions in php
PDF
DOCX
Java practical
PPSX
Php and MySQL
SQLITE Android
JavaScript Promises
Class 3 - PHP Functions
Sessions in php
Java practical
Php and MySQL

What's hot (20)

PPTX
Access specifiers(modifiers) in java
PPT
Php forms
PPT
Node.js Express Framework
PPT
PHP - Introduction to PHP Forms
PPT
PHP - Introduction to File Handling with PHP
PDF
Java IO
PDF
Java exception-handling
PPT
Java Basics
PPT
Applet life cycle
PPTX
Node.js Express
PDF
JavaScript - Chapter 6 - Basic Functions
PPTX
PPT
PHP variables
PPTX
Html forms
PDF
Java - Exception Handling Concepts
PPSX
Exception Handling
PPTX
Uploading a file with php
PPT
PHP complete reference with database concepts for beginners
Access specifiers(modifiers) in java
Php forms
Node.js Express Framework
PHP - Introduction to PHP Forms
PHP - Introduction to File Handling with PHP
Java IO
Java exception-handling
Java Basics
Applet life cycle
Node.js Express
JavaScript - Chapter 6 - Basic Functions
PHP variables
Html forms
Java - Exception Handling Concepts
Exception Handling
Uploading a file with php
PHP complete reference with database concepts for beginners
Ad

Viewers also liked (6)

PDF
Php tutorial
PPT
Functions in php
PDF
Abstract Class and Interface in PHP
PDF
Php Tutorials for Beginners
PDF
Functions in PHP
PDF
Sorting arrays in PHP
Php tutorial
Functions in php
Abstract Class and Interface in PHP
Php Tutorials for Beginners
Functions in PHP
Sorting arrays in PHP
Ad

Similar to PHP Functions & Arrays (20)

PPT
Php Chapter 2 3 Training
PDF
Php tips-and-tricks4128
PPTX
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
PDF
php AND MYSQL _ppt.pdf
PDF
The History of PHPersistence
PPT
Arrays in php
KEY
Good Evils In Perl (Yapc Asia)
PPT
PHP and MySQL
PDF
Web 8 | Introduction to PHP
PDF
JavaScript for PHP developers
PPT
Php my sql - functions - arrays - tutorial - programmerblog.net
PDF
Scripting3
PPTX
PHP PPT FILE
PPTX
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
PPTX
UNIT IV (4).pptx
PDF
Adventures in Optimization
DOCX
20220112 sac v1
PDF
[PL] Jak nie zostać "programistą" PHP?
PPTX
Array functions for all languages prog.pptx
Php Chapter 2 3 Training
Php tips-and-tricks4128
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
php AND MYSQL _ppt.pdf
The History of PHPersistence
Arrays in php
Good Evils In Perl (Yapc Asia)
PHP and MySQL
Web 8 | Introduction to PHP
JavaScript for PHP developers
Php my sql - functions - arrays - tutorial - programmerblog.net
Scripting3
PHP PPT FILE
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
UNIT IV (4).pptx
Adventures in Optimization
20220112 sac v1
[PL] Jak nie zostać "programistą" PHP?
Array functions for all languages prog.pptx

More from Henry Osborne (20)

PPTX
Android Fundamentals
PPTX
Open Source Education
PPTX
Security Concepts - Linux
PPTX
Networking Basics with Linux
PPTX
Disk and File System Management in Linux
PPTX
Drawing with the HTML5 Canvas
PPTX
HTML5 Multimedia Support
PPTX
Information Architecture
PPTX
Interface Design
PPTX
Universal Usability
PPTX
Website Security
PPTX
XML and Web Services
PPTX
Elements of Object-oriented Design
PPTX
Database Programming
PPTX
OOP in PHP
PPTX
Web Programming
PPTX
PHP Strings and Patterns
PPTX
PHP Basics
PPTX
Activities, Fragments, and Events
PPTX
Establishing a Web Presence
Android Fundamentals
Open Source Education
Security Concepts - Linux
Networking Basics with Linux
Disk and File System Management in Linux
Drawing with the HTML5 Canvas
HTML5 Multimedia Support
Information Architecture
Interface Design
Universal Usability
Website Security
XML and Web Services
Elements of Object-oriented Design
Database Programming
OOP in PHP
Web Programming
PHP Strings and Patterns
PHP Basics
Activities, Fragments, and Events
Establishing a Web Presence

Recently uploaded (20)

PPTX
Copy of ARAL Program Primer_071725(1).pptx
PDF
BSc-Zoology-02Sem-DrVijay-Comparative anatomy of vertebrates.pdf
PPTX
ACFE CERTIFICATION TRAINING ON LAW.pptx
PPTX
2025 High Blood Pressure Guideline Slide Set.pptx
PDF
Physical pharmaceutics two in b pharmacy
PPTX
Neurology of Systemic disease all systems
PPTX
Approach to a child with acute kidney injury
DOCX
THEORY AND PRACTICE ASSIGNMENT SEMESTER MAY 2025.docx
PPTX
Key-Features-of-the-SHS-Program-v4-Slides (3) PPT2.pptx
DOCX
EDUCATIONAL ASSESSMENT ASSIGNMENT SEMESTER MAY 2025.docx
PDF
Unleashing the Potential of the Cultural and creative industries
PDF
Disorder of Endocrine system (1).pdfyyhyyyy
PPTX
Thinking Routines and Learning Engagements.pptx
PPTX
operating_systems_presentations_delhi_nc
PDF
WHAT NURSES SAY_ COMMUNICATION BEHAVIORS ASSOCIATED WITH THE COMP.pdf
PPTX
IT infrastructure and emerging technologies
PDF
faiz-khans about Radiotherapy Physics-02.pdf
PPTX
Neurological complocations of systemic disease
PPTX
Theoretical for class.pptxgshdhddhdhdhgd
PDF
Diabetes Mellitus , types , clinical picture, investigation and managment
Copy of ARAL Program Primer_071725(1).pptx
BSc-Zoology-02Sem-DrVijay-Comparative anatomy of vertebrates.pdf
ACFE CERTIFICATION TRAINING ON LAW.pptx
2025 High Blood Pressure Guideline Slide Set.pptx
Physical pharmaceutics two in b pharmacy
Neurology of Systemic disease all systems
Approach to a child with acute kidney injury
THEORY AND PRACTICE ASSIGNMENT SEMESTER MAY 2025.docx
Key-Features-of-the-SHS-Program-v4-Slides (3) PPT2.pptx
EDUCATIONAL ASSESSMENT ASSIGNMENT SEMESTER MAY 2025.docx
Unleashing the Potential of the Cultural and creative industries
Disorder of Endocrine system (1).pdfyyhyyyy
Thinking Routines and Learning Engagements.pptx
operating_systems_presentations_delhi_nc
WHAT NURSES SAY_ COMMUNICATION BEHAVIORS ASSOCIATED WITH THE COMP.pdf
IT infrastructure and emerging technologies
faiz-khans about Radiotherapy Physics-02.pdf
Neurological complocations of systemic disease
Theoretical for class.pptxgshdhddhdhdhgd
Diabetes Mellitus , types , clinical picture, investigation and managment

PHP Functions & Arrays

  • 3. Basic Syntax function name() { } function hello() { echo “Hello World!”; } hello();
  • 4. Returning Values function hello() { return “Hello World!”; } $txt = hello(); echo hello();
  • 5. Returning Values function hello() { echo “Hello $who”; if ($who == “World”) { return; } echo “, how are you?”; } hello (“World”); //Displays “Hello World” hello (“Reader”); //Displays “Hello Reader, how are you?”
  • 6. Returning Values function &query($sql) { $result = mysql_query($sql); return $result; } //The following is incorrect and will cause PHP to emit a notice when called. function &getHello() { return “Hello World”; } //This will also cause the warning to be issued when called function &test() { echo „This is a test‟; }
  • 7. Variable Scope • Three variable scopes exist: • Global • Function • Class
  • 8. Variable Scope, cont’d $a = “Hello World”; function hello() { $a = “Hello Reader”; $b = “How are you?”; } hello (); echo $a; //Will output Hello World echo $b; //Will emit a warning
  • 9. Variable Scope, cont’d $a = “Hello”; $b = “World”; function hello() { global $a, $b; echo “$a $b”; } hello (); //Displays Hello World
  • 10. Variable Scope, cont’d $a = “Hello”; $b = “World”; function hello() { echo $GLOBALS[„a‟].‟ „.$GLOBALS[„b‟]; } hello (); //Displays Hello World
  • 11. Variable-Length Argument Lists function hello() { if (func_num_args() > 0) { $arg = func_get_arg(0); echo “Hello $arg”; } else { echo ”Hello World”; } } hello(“Reader);
  • 12. Variable-Length Argument Lists function countAll($arg1){ if (func_num_args() == 0) { die(“You need to specify at least one argument”); } else { $args = func_get_args(); array_shift($args); $count = strlen($arg1); foreach ($args as $arg) { $count += strlen($arg); } } return $count; } echo countAll(“apple”,”pear”, “plum”);
  • 13. Passing Arguments by Reference function countAll(&$count){ if (func_num_args() == 0) { die(“You need to specify at least one argument”); } else { $args = func_get_args(); array_shift($args); $count = strlen($arg1); foreach ($args as $arg) { $count += strlen($arg); } } } $count = 0; countAll($count, “apple”,”pear”, “plum”); //count now equals 13
  • 15. Array Basics $a = array (10, 20, 30); $a = array (‟a‟ => 10, ‟b‟ => 20, ‟cee‟ => 30); $a = array (5 => 1, 3 => 2, 1 => 3,); $a = array();
  • 16. Array Basics $x[] = 10; $x[‟aa‟] = 11; echo $x[0]; // Outputs 10
  • 17. Printing Arrays • PHP provides two functions that can be used to output a variable’s value recursively • print_r() • var_dump().
  • 18. Enumerative vs Associative • Arrays can be roughly divided in two categories: enumerative and associative. • Enumerative arrays are indexed using only numerical indexes • Associative arrays(sometimes referred to as dictionaries) allow the association of an arbitrary key to every element.
  • 19. Enumerative vs Associative, cont’d When an element is added to an array without specifying a key, PHP automatically assigns a numeric one that is equal to the greatest numeric key already in existence in the array, plus one: $a = array (2 => 5); $a[] = ‟a‟; // This will have a key of 3 $a = array (‟4‟ => 5, ‟a‟ => ‟b‟); $a[] = 44; // This will have a key of 5
  • 20. Array keys are case-sensitive, but type insensitive. Thus, the key ’A’ is different from the key ’a’, but the keys ’1’ and 1 are the same. However, the conversion is only applied if a string key contains the traditional decimal representation of a number; thus, for example, the key ’01’ is not the same as the key 1. NOTE WELL
  • 21. Multi-dimensional Arrays $array = array(); $array[] = array(‟foo‟, ‟bar‟); $array[] = array(‟baz‟, ‟bat‟); echo $array[0][1] . $array[1][0]; //output is barbaz
  • 22. Unravelling Arrays $sql = "SELECT user_first, user_last, lst_log FROM users"; $result = mysql_query($sql); while (list($first, $last, $last_login) = mysql_fetch_row($result)) { echo "$last, $first - Last Login: $last_login"; }
  • 23. array(6) { [0]=> Array Operations int(1) [1]=> int(2) [2]=> $a = array (1, 2, 3); int(3) $b = array (‟a‟ => 1, ‟b‟ => 2, ‟c‟ => 3); ["a"]=> var_dump ($a + $b); int(1) ["b"]=> int(2) ["c"]=> int(3) }
  • 24. Array Operations, cont’d array(4) { [0]=> int(1) $a = array (1, 2, 3); [1]=> $b = array (‟a‟ => 1, 2, 3); int(2) var_dump ($a + $b); [2]=> int(3) ["a"]=> int(1) }
  • 25. Comparing Arrays $a = array (1, 2, 3); $b = array (1 => 2, 2 => 3, 0 => 1); $c = array (‟a‟ => 1, ‟b‟ => 2, ‟c‟ => 3); var_dump ($a == $b); // True var_dump ($a === $b); // False var_dump ($a == $c); // False var_dump ($a === $c); // False
  • 26. Comparing Arrays, cont’d $a = array (1, 2, 3); $b = array (1 => 2, 2 => 3, 0 => 1); var_dump ($a != $b); // False var_dump ($a !== $b); // True
  • 27. Counting, Searching and Deleting Elements $a = array (1, 2, 4); $b = array(); $c = 10; echo count ($a); // Outputs 3 echo count ($b); // Outputs 0 echo count ($c); // Outputs 1
  • 28. Counting, Searching and Deleting Elements, cont’d $a = array (‟a‟ => 1, ‟b‟ => 2); echo isset ($a[‟a‟]); // True echo isset ($a[‟c‟]); // False $a = array (‟a‟ => NULL, ‟b‟ => 2); echo isset ($a[‟a‟]); // False
  • 29. Counting, Searching and Deleting Elements, cont’d $a = array (‟a‟ => NULL, ‟b‟ => 2); echo array_key_exists (‟a‟, $a); // True $a = array (‟a‟ => NULL, ‟b‟ => 2); echo in_array (2, $a); // True
  • 30. Counting, Searching and Deleting Elements, cont’d $a = array (‟a‟ => NULL, ‟b‟ => 2); unset ($a[‟b‟]); echo in_array ($a, 2); // False
  • 31. Flipping and Reversing $a = array (‟a‟, ‟b‟, ‟c‟); array(3) {{ array(3) ["a"]=> [0]=> int(0) string(1) "c" ["b"]=> [1]=> int(1) string(1) "b" ["c"]=> ["x"]=> int(2) string(1) "a" var_dump (array_flip ($a)); $a = array (‟x‟ => ‟a‟, 10 => ‟b‟, ‟c‟); var_dump (array_reverse ($a)); }}
  • 32. Array Iteration • One of the most common operations you will perform with arrays • PHP arrays require a set of functionality that matches their flexibility • “normal” looping structures cannot cope with the fact that array keys do not need to be continuous $a = array (‟a‟ => 10, 10 => 20, ‟c‟ => 30);
  • 33. Array Iteration: Array Pointer $array = array(‟foo‟ => ‟bar‟, ‟baz‟, ‟bat‟ => 2); function displayArray(&$array) { reset($array); while (key($array) !== null) { echo key($array) .": " .current($array) . PHP_EOL; next($array); } }
  • 34. Array Iteration: foreach $array = array(‟foo‟, ‟bar‟, ‟baz‟); foreach ($array as $key => $value) { echo "$key: $value"; }
  • 35. array(2) { ["internal"]=> Passive Iteration &array(3) { [0]=> string(3) "RSS" [1]=> function setCase(&$value, &$key) string(4) "HTML" { [2]=> string(3) "XML" $value = strtoupper($value); } } ["custom"]=> $type = array(‟internal‟, ‟custom‟); &array(2) { $output_formats[] = array(‟rss‟, ‟html‟, ‟xml‟); [0]=> $output_formats[] = array(‟csv‟, ‟json‟); string(3) "CSV" $map = array_combine($type, $output_formats); [1]=> array_walk_recursive($map, ‟setCase‟); string(4) "JSON" } var_dump($map); }
  • 36. Sorting Arrays: sort() $array = array(‟a‟ => ‟foo‟, ‟b‟ => ‟bar‟, ‟c‟ => ‟baz‟); sort($array); array(3) { [0]=> var_dump($array); string(3) "bar" [1]=> string(3) "baz" [2]=> string(3) "foo" }
  • 37. Sorting Arrays: asort() $array = array(‟a‟ => ‟foo‟, ‟b‟ => ‟bar‟, ‟c‟ => ‟baz‟); asort($array); var_dump($array); array(3) { ["b"]=> string(3) "bar" ["c"]=> string(3) "baz" ["a"]=> string(3) "foo“ }
  • 38. Sorting Arrays SORT_REGULAR Compare items as they appear in the array, without performing any kind of conversion. This is the default behaviour. SORT_NUMERIC Convert each element to a numeric value for sorting purposes. SORT_STRING Compare all elements as strings.
  • 39. Sorting Arrays: natsort() $array = array(‟10t‟, ‟2t‟, ‟3t‟); natsort($array); array(3) { [1]=> var_dump($array); string(2) "2t" [2]=> string(2) "3t" [0]=> string(3) "10t" }
  • 40. Anti-Sorting: shuffle() $cards = array (1, 2, 3, 4); array(4) { [0]=> shuffle($cards); int(4) var_dump($cards); [1]=> int(1) [2]=> int(2) [3]=> int(3) }
  • 41. Anti-Sorting: array_keys() $cards = array (‟a‟ => 10, ‟b‟ => 12, ‟c‟ => 13); $keys = array_keys ($cards); shuffle($keys); foreach ($keys as $v) { echo $v . " - " . $cards[$v] . "n"; }
  • 42. Anti-Sorting: array_rand() $cards = array (‟a‟ => 10, ‟b‟ => 12, ‟c‟ =>array(2) { { 13); array(3) $keys = array_rand ($cards, 2); ["a"]=> [0]=> int(10) string(1) "a" ["b"]=> [1]=> var_dump($keys); int(12) string(1) "b" var_dump($cards); ["c"]=> } int(13) }
  • 43. Arrays as Stacks, Queues and Sets $stack = array(); array_push($stack, ‟bar‟, ‟baz‟); var_dump($stack); $last_in = array_pop($stack); var_dump($last_in, $stack);
  • 44. Arrays as Stacks, Queues and Sets array(2) { [0]=> $queue = array(‟qux‟, ‟bar‟, ‟baz‟); string(3) "bar" [1]=> $first_element = array_shift($queue); var_dump($queue); string(3) "baz" } array(3) { array_unshift($queue, ‟foo‟); [0]=> string(3) "foo" var_dump($queue); [1]=> string(3) "bar" [2]=> string(3) "baz" }
  • 45. Set Functionality $a = array (1, 2, 3); $b = array (1, 3, 4); var_dump (array_diff ($a, $b)); var_dump (array_intersect ($a, $b));

Editor's Notes

  • #3: Functions are the heart of PHP programmingThe ability to encapsulate any piece of code that it can be called repeatedly is invaluable
  • #7: Functions can also be declared that they return by referenceAllows the return of a variable instead of a copyOne caveat: a variable must be returned
  • #8: Global: defined outside any function or class; accessible/available throughout lifecycle of programFunction: defined within a function; unavailable after function execution
  • #10: To access global variables within a function two ways exist:“import” the variable using the global keywordusing the superglobal array
  • #11: Some programmers prefer to use the $GLOBALS superglobal array, which contains all the variables in a global scope.
  • #12: PHP provides three functions to handle variable-length argument lists:func_num_args()func_get_arg()func_get_args()
  • #13: It’s nearly impossible to provide comprehensive test cases if a function that accepts a variable number of arguments isn’t constructed properly.
  • #15: All arrays are ordered collections of item, called elementsPHP arrays are extremely flexible allowing numeric keys, auto-incremented keys, alpha-numeric keysCapable of storing practically any value, including other arraysOver 70 functions for array manipulation
  • #16: Arrays are created one of two waysThe first line of code creates an array by only specifying the values of its three elements. Since every element of an array must also have a key, PHP automatically assigns a numeric key to each element, starting from zero. In the second example, the array keys are specified in the call to array()—in this case, three alphabetical keys (note that the length of the keys is arbitrary).In the third example, keys are assigned “out of order,” so that the first element of the array has, in fact, the key 5—note here the use of a “dangling comma” after the last element, which is perfectly legal from a syntactical perspective and has no effect on the final array. Finally, in the fourth example creates an empty array.
  • #17: The second method of accessing arrays is by means of the array operator ([ ])
  • #18: While both functions recursively print out the contents of composite value, only var_dump() outputs the data types of each valueOnly var_dump() is capable of outputting the value of more than one variable at the same timeOnly print_r can return its output as a string, as opposed to writing it to the script’s standard outputGenerally speaking, echo will cover most output requirements, while var_dump() and print_r() offer a more specialized set of functionality that works well as an aid in debugging.
  • #19: In PHP, this distinction is significantly blurred, as you can create an enumerative array and then add associative elements to it (while still maintaining elements of an enumeration). What’s more, arrays behave more like ordered maps and can actually be used to simulate a number of different structures, including queues and stacks.
  • #20: PHP provides a great amount of flexibility in how numeric keys can be assigned to arraysCan be any integer number (both negative and positive)Don’t need to be sequential, so that a large gap can exist between the indices of two consecutive values without the need to create intermediate values to cover everypossible key in between.
  • #22: To create multi-dimensional arrays, simply assign an array as the value for an array element. With PHP, we can do this for one or more elements within any array—thus allowing for infinite levels of nesting.
  • #23: It is sometimes simpler to work with the values of an array by assigning them to individual variables.While this can be accomplished by extracting individual elements and assigning each to a different variable, PHP provides a quick shortcut, the list() construct
  • #24: The addition operator + can be used to create the union of its two operands
  • #25: If the two arrays had common keys (either string or numeric), they would only appear once in the end result
  • #26: Array-to-array comparison is a relatively rare occurrence, but it can be performed using another set of operators.The equivalence operator == returns true if both arrays have the same number of elements with the same values and keys, regardless of their order.The identity operator ===, on the other hand, returns true only if the array contains the same key/value pairs in the same order.
  • #27: Inequality operator only ensures that both arrays contain the same elements with the same keys, whereas the non-identity operator also verifies their position.
  • #28: The size of an array can be retrieved by calling the count() functioncount() cannot be used to determine whether a variable contains an array—since running it on a scalar value will return one. The right way to tell whether a variable contains an array is to use is_array() instead.
  • #29: A similar problem exists with determining whether an element with the given key exists. This is often done by calling isset()However, isset() has the major drawback of considering an element whose value is NULL—which is perfectly valid—as inexistent:
  • #30: The correct way to determine whether an array element exists is to use array_key_exists() in_array() function: determine whether an element with a given value exists in an array
  • #31: An element can be deleted from an array by unsetting it
  • #32: Two functions that have rather confusing names and that are sometimes misused: array_flip() and array_reverse()array_flip(): inverts the value of each element of an array with its keyarray_reverse(): inverts the order of the array’s elements, so that the last one appears first
  • #34: We have created a function that will display all the values in an array. First, we call reset() to rewind the internal array pointer. Next, using a while loop, we display the current key and value, using the key() and current() functions. Finally, we advance the array pointer, using next(). The loop continues until we no longer have a valid key.
  • #35: We have created a function that will display all the values in an array. First, we call reset() to rewind the internal array pointer. Next, using a while loop, we display the current key and value, using the key() and current() functions. Finally, we advance the array pointer, using next(). The loop continues until we no longer have a valid key.
  • #36: The array_walk() function and its recursive cousin array_walk_recursive() can be used to perform an iteration of an array in which a user-defined function is called.One thing to note about array_walk_recursive() is that it will not call the user-defined function on anything but scalar values; because of this, the first set of keys, internal and custom, are never passed in.
  • #37: total of 11 functions in the PHP core whose only goal is to provide various methods of sorting the contents of an arraysort() effectively destroys all the keys in the array and renumbers its elements starting from zero
  • #38: If you wish to maintain key association, you can use asort() insteadBoth sort() and asort() sort values in ascending order. To sort them in descending order, you can use rsort() and arsort().
  • #39: Both sort() and asort() accept a second, optional parameter that allows you to specify how the sort operation takes place
  • #40: The sorting operation performed by sort() and asort() simply takes into consideration either the numeric value of each element, or performs a byte-by-byte comparison of strings values. This can result in an “unnatural” sorting order—for example, the string value ’10t’ will be considered “lower” than ’2t’ because it starts with the character 1, which has a lower value than 2. If this sorting algorithm doesn’t work well for your needs, you can try using natsort() insteadThe natsort() function will, unlike sort(), maintain all the key-value associations in the array.
  • #41: The key-value association is lost; however, this problem is easily over-come by using another array function—array_keys()
  • #42: Returns an array whose values are the keys of the array passed to it
  • #43: Returns one or more random keys from an array
  • #44: Arrays are often used as stacks (Last In, First Out, or LIFO) and queue (First In, First Out, or FIFO) structures. PHP simplifies this approach by providing a set of functions can be used to push and pop (for stacks) and shift and unshift (for queues) elements from an array.In this example, we first, create an array, and we then add two elements to it using array_push(). Next, using array_pop(), we extract the last element added to the array.
  • #45: If you intend to use an array as a queue (FIFO), you can add elements at the be-ginning using array_unshift() and remove them again using array_shift()
  • #46: Some PHP functions are designed to perform set operations on arrays. For example, array_diff() is used to compute the difference between two arraysThe call to array_diff() will cause all the values of $a that do not also appear in $b to be retained, while everything else is discardedConversely to array_diff(), array_intersect() will compute the intersection be-tween two arrays