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 Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Php forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiPhp forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligeti
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Php array
Php arrayPhp array
Php array
 
Chapter 02 php basic syntax
Chapter 02   php basic syntaxChapter 02   php basic syntax
Chapter 02 php basic syntax
 
Web Technology Lab File
Web Technology Lab FileWeb Technology Lab File
Web Technology Lab File
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Php introduction
Php introductionPhp introduction
Php introduction
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
Php with mysql ppt
Php with mysql pptPhp with mysql ppt
Php with mysql ppt
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 

Viewers also liked

Viewers also liked (6)

Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Abstract Class and Interface in PHP
Abstract Class and Interface in PHPAbstract Class and Interface in PHP
Abstract Class and Interface in PHP
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 

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
 
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
 
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
 

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

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 

Recently uploaded (20)

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 

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