SlideShare a Scribd company logo
1 of 46
Functions & Arrays
Henry Osborne
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

What's hot (20)

PHP variables
PHP  variablesPHP  variables
PHP variables
 
Php introduction
Php introductionPhp introduction
Php introduction
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
Lesson 5 php operators
Lesson 5   php operatorsLesson 5   php operators
Lesson 5 php operators
 
Php forms
Php formsPhp forms
Php forms
 
Php array
Php arrayPhp array
Php array
 
PHP
PHPPHP
PHP
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
 
Php string function
Php string function Php string function
Php string function
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Php functions
Php functionsPhp functions
Php functions
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 

Similar to Functions & Arrays: PHP Guide to Basic Syntax, Returning Values, Variable Scope, and More

Similar to Functions & Arrays: PHP Guide to Basic Syntax, Returning Values, Variable Scope, and More (20)

Intoduction to php arrays
Intoduction to php arraysIntoduction to php arrays
Intoduction to php arrays
 
Php Chapter 2 3 Training
Php Chapter 2 3 TrainingPhp Chapter 2 3 Training
Php Chapter 2 3 Training
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
Scripting3
Scripting3Scripting3
Scripting3
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?
 
Intermediate PHP
Intermediate PHPIntermediate PHP
Intermediate PHP
 

More from Henry Osborne

Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android FundamentalsHenry Osborne
 
Open Source Education
Open Source EducationOpen Source Education
Open Source EducationHenry Osborne
 
Security Concepts - Linux
Security Concepts - LinuxSecurity Concepts - Linux
Security Concepts - LinuxHenry Osborne
 
Networking Basics with Linux
Networking Basics with LinuxNetworking Basics with Linux
Networking Basics with LinuxHenry Osborne
 
Disk and File System Management in Linux
Disk and File System Management in LinuxDisk and File System Management in Linux
Disk and File System Management in LinuxHenry Osborne
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 CanvasHenry Osborne
 
HTML5 Multimedia Support
HTML5 Multimedia SupportHTML5 Multimedia Support
HTML5 Multimedia SupportHenry Osborne
 
Information Architecture
Information ArchitectureInformation Architecture
Information ArchitectureHenry Osborne
 
XML and Web Services
XML and Web ServicesXML and Web Services
XML and Web ServicesHenry Osborne
 
Elements of Object-oriented Design
Elements of Object-oriented DesignElements of Object-oriented Design
Elements of Object-oriented DesignHenry Osborne
 
Database Programming
Database ProgrammingDatabase Programming
Database ProgrammingHenry Osborne
 
PHP Strings and Patterns
PHP Strings and PatternsPHP Strings and Patterns
PHP Strings and PatternsHenry Osborne
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and EventsHenry Osborne
 
Establishing a Web Presence
Establishing a Web PresenceEstablishing a Web Presence
Establishing a Web PresenceHenry Osborne
 

More from Henry Osborne (20)

Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android Fundamentals
 
Open Source Education
Open Source EducationOpen Source Education
Open Source Education
 
Security Concepts - Linux
Security Concepts - LinuxSecurity Concepts - Linux
Security Concepts - Linux
 
Networking Basics with Linux
Networking Basics with LinuxNetworking Basics with Linux
Networking Basics with Linux
 
Disk and File System Management in Linux
Disk and File System Management in LinuxDisk and File System Management in Linux
Disk and File System Management in Linux
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
 
HTML5 Multimedia Support
HTML5 Multimedia SupportHTML5 Multimedia Support
HTML5 Multimedia Support
 
Information Architecture
Information ArchitectureInformation Architecture
Information Architecture
 
Interface Design
Interface DesignInterface Design
Interface Design
 
Universal Usability
Universal UsabilityUniversal Usability
Universal Usability
 
Website Security
Website SecurityWebsite Security
Website Security
 
XML and Web Services
XML and Web ServicesXML and Web Services
XML and Web Services
 
Elements of Object-oriented Design
Elements of Object-oriented DesignElements of Object-oriented Design
Elements of Object-oriented Design
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Web Programming
Web ProgrammingWeb Programming
Web Programming
 
PHP Strings and Patterns
PHP Strings and PatternsPHP Strings and Patterns
PHP Strings and Patterns
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and Events
 
Establishing a Web Presence
Establishing a Web PresenceEstablishing a Web Presence
Establishing a Web Presence
 

Recently uploaded

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Functions & Arrays: PHP Guide to Basic Syntax, Returning Values, Variable Scope, and More

  • 2.
  • 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

  1. Functions are the heart of PHP programmingThe ability to encapsulate any piece of code that it can be called repeatedly is invaluable
  2. 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
  3. Global: defined outside any function or class; accessible/available throughout lifecycle of programFunction: defined within a function; unavailable after function execution
  4. To access global variables within a function two ways exist:“import” the variable using the global keywordusing the superglobal array
  5. Some programmers prefer to use the $GLOBALS superglobal array, which contains all the variables in a global scope.
  6. PHP provides three functions to handle variable-length argument lists:func_num_args()func_get_arg()func_get_args()
  7. It’s nearly impossible to provide comprehensive test cases if a function that accepts a variable number of arguments isn’t constructed properly.
  8. 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
  9. 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.
  10. The second method of accessing arrays is by means of the array operator ([ ])
  11. 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.
  12. 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.
  13. 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.
  14. 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.
  15. 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
  16. The addition operator + can be used to create the union of its two operands
  17. If the two arrays had common keys (either string or numeric), they would only appear once in the end result
  18. 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.
  19. Inequality operator only ensures that both arrays contain the same elements with the same keys, whereas the non-identity operator also verifies their position.
  20. 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.
  21. 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:
  22. 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
  23. An element can be deleted from an array by unsetting it
  24. 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
  25. 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.
  26. 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.
  27. 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.
  28. 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
  29. 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().
  30. Both sort() and asort() accept a second, optional parameter that allows you to specify how the sort operation takes place
  31. 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.
  32. The key-value association is lost; however, this problem is easily over-come by using another array function—array_keys()
  33. Returns an array whose values are the keys of the array passed to it
  34. Returns one or more random keys from an array
  35. 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.
  36. 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()
  37. 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