SlideShare a Scribd company logo
1 of 22
PHP Functions
and
Arrays
Orlando PHP Meetup
Zend Certification Training
March 2009
Functions
Minimal syntax
function name() { }
PHP function names are not case-
sensitive.
All functions in PHP return a value—even
if you don’t explicitly cause them to.
No explicit return value returns NULL
“return $value;” exits function immediately.
Variable Scope
Global scope
A variable declared or first used outside of a function or
class has global scope.
NOT visible inside functions by default.
Use “global $varname;” to make a global variable visible
inside a function.
Function scope
Declared or passed in via function parameters.
A visible throughout the function, then discarded when
the function exits.
Case scope
Stay tuned for Object Oriented chapter…
Scope (continued)
Global
$a = "Hello";
$b = "World";
function hello() {
global $a, $b;
echo "$a $b";
echo $GLOBALS[’a’] .’ ’.
$GLOBALS[’b’];
}
Scope (continued)
Regular Parameters
function hello($who = "World") {
echo "Hello $who";
}
Variable Length Parameters
func_num_args(), func_get_arg() and
func_get_args()
function hello() {
if (func_num_args() > 0) {
$arg = func_get_arg(0); // The
first argument is at position 0
echo "Hello $arg";
} else {
echo "Hello World";
}
Passing Arguments by
ReferencePrefix a parameter with an “&”
Function func (&$variable) {}
Changes to the variable will persist after the function
call
function cmdExists($cmd, &$output =
null) {
$output = ‘whereis $cmd‘;
if (strpos($output,
DIRECTORY_SEPARATOR) !== false) {
return true;
} else {
return false;
}
}
Function Summary
Declare functions with parameters and
return values
By default, parameters and variables have
function scope.
Pass parameters by reference to return
values to calling function.
Parameters can have default values. If no
default identified, then parameter must be
passed in or an error will be thrown.
Parameter arrays are powerful but hard to
debug.
Arrays
All arrays are ordered collections of
items, called elements.
Has a value, identified by a unique key (integer
or case sensitive string)
Keys
By default, keys start at zero
String can be of any length
Value can be any variable type (string,
number, object, resource, etc.)
Declaring Arrays
Explicit
$a = array (10, 20, 30);
$a = array (’a’ => 10, ’b’ =>
20, ’cee’ => 30);
$a = array (5 => 1, 3 => 2, 1
=> 3,);
$a = array(); //Empty
Implicit
$x[] = 10; //Gets next
available int index, 0
$x[] = 11; //Next index, 1
$x[’aa’] = 11;
Printing Arrays
print_r()
Recursively prints the values
May return value as a string to assign to a
variable.
Var_dump()
outputs the data types of each value
Can only echo immediately
Enumerative vs.
Associative
Enumerative
Integer indexes, assigned sequentially
When no key given, next key = max(integer keys) + 1
Associative
Integer or String keys, assigned specifically
Keys are case sensitive but type insensitive
‘a’ != ‘A’ but ‘1’ == 1
Mixed
$a = array (’4’ => 5, ’a’ => ’b’);
$a[] = 44; // This will have a key of 5
Multi-dimensional
Arrays
Array item value is another array
$array = array();
$array[] = array(’foo’,’bar’);
$array[] = array(’baz’,’bat’);
echo $array[0][1] . $array[1]
[0];
Unraveling Arrays
list() operator
Receives the results of an array
List($a, $b, $c) = array(‘one’, ‘two’, ‘three’);
Assigns $a = ‘one’, $b = ‘two’, $c = ‘three’
Useful for functions that return an array
list($first, $last,
$last_login) =
mysql_fetch_row($result);
Comparing Arrays
Equal (==)
Arrays must have the same number and value
of keys and values, but in any order
Exactly Equal (===)
Arrays must have the same number and value
of keys and values and in the exact same order.
Counting, Searching
and Deleting Elements
count($array)
Returns the number of elements in the first
level of the array.
array_key_exists($key, $array)
If array element with key exists, returns
TRUE, even if value is NULL
in_array($value, $array)
If the value is in the array, returns TRUE
unset($array[$key])
Removes the element from the array.
Flipping and Reversing
array_flip($array)
Swaps keys for values
Returns a new array
array_reverse($array)
Reverses the order of the key/value pairs
Returns a new array
Don’t confuse the two, like I usually do
Array Iteration
The Array Pointer
reset(), end(), next(), prev(), current(), key()
An Easier Way to Iterate
foreach($array as $value) {}
foreach($array as $key=>$value){}
Walk the array and process each value
array_walk($array, ‘function name to call’);
array_walk_recursive($array, ‘function’);
Sorting Arrays
There are eleven sorting functions in PHP
sort($array)
Sorts the array in place and then returns.
All keys become integers 0,1,2,…
asort($array)
Sorts the array in place and returns
Sorts on values, but leaves key assignments in
place.
rsort() and arsort() to reverse sort.
ksort() and krsort() to sort by key, not value
Sorting (continued)
usort($array, ‘compare_function’)
Compare_function($one, $two) returns
-1 if $one < $two
0 if $one == $two
1 if $one > $two
Great if you are sorting on a special function,
like length of the strings or age or something
like that.
uasort() to retain key=>value association.
shuffle($array) is the anti-sort
Arrays as Stacks,
Queues and Sets
Stacks (Last in, first out)
array_push($array, $value [, $value2] )
$value = array_pop($array)
Queue (First in, first out)
array_unshift($array, $value [, $value2] )
$value = array_shift($array)
Set Functionality
$array = array_diff($array1, $array2)
$array = array_intersect($a1, $a2)
Summary
Arrays are probably the single most
powerful data management tool available
to PHP developers. Therefore, learning to
use them properly is essential for a good
developer.
Some methods are naturally more
efficient than others. Read the function
notes to help you decide.
Look for ways in your code to use arrays
to reduce code and improve flexibility.
Thank You
Shameless Plug
15 years of development experience, 14 of that
running my own company.
I am currently available for new contract work
in PHP and .NET.
cchubb@codegurus.com

More Related Content

What's hot

Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHPAhmed Swilam
 
Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in phpAshish Chamoli
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requireTheCreativedev Blog
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021Ayesh Karunaratne
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisIan Macali
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database ProgrammingAhmed Swilam
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...anshkhurana01
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 TrainingChris Chubb
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedAyesh Karunaratne
 

What's hot (20)

Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in php
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
PHP function
PHP functionPHP function
PHP function
 
DIG1108 Lesson 6
DIG1108 Lesson 6DIG1108 Lesson 6
DIG1108 Lesson 6
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Operators in PHP
Operators in PHPOperators in PHP
Operators in PHP
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 Training
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changed
 

Similar to Php Chapter 2 3 Training (20)

PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Scripting3
Scripting3Scripting3
Scripting3
 
Chap 3php array part 3
Chap 3php array part 3Chap 3php array part 3
Chap 3php array part 3
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
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
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashes
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Marcs (bio)perl course
Marcs (bio)perl courseMarcs (bio)perl course
Marcs (bio)perl course
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
Intoduction to php arrays
Intoduction to php arraysIntoduction to php arrays
Intoduction to php arrays
 
Php2
Php2Php2
Php2
 
Introduction to perl_lists
Introduction to perl_listsIntroduction to perl_lists
Introduction to perl_lists
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Intoduction to php strings
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 

More from Chris Chubb

Red beanphp orm presentation
Red beanphp orm presentationRed beanphp orm presentation
Red beanphp orm presentationChris Chubb
 
Portfolio Public Affairs Council
Portfolio   Public Affairs CouncilPortfolio   Public Affairs Council
Portfolio Public Affairs CouncilChris Chubb
 
Portfolio Pact Publications
Portfolio   Pact PublicationsPortfolio   Pact Publications
Portfolio Pact PublicationsChris Chubb
 
Portfolio Npf Web Site Donate
Portfolio   Npf Web Site DonatePortfolio   Npf Web Site Donate
Portfolio Npf Web Site DonateChris Chubb
 
Portfolio Webposition
Portfolio   WebpositionPortfolio   Webposition
Portfolio WebpositionChris Chubb
 
Portfolio Link Popularity Check
Portfolio   Link Popularity CheckPortfolio   Link Popularity Check
Portfolio Link Popularity CheckChris Chubb
 
Portfolio Npf Ms Batch Loader
Portfolio   Npf Ms Batch LoaderPortfolio   Npf Ms Batch Loader
Portfolio Npf Ms Batch LoaderChris Chubb
 
Portfolio Npf Buy Site
Portfolio   Npf Buy SitePortfolio   Npf Buy Site
Portfolio Npf Buy SiteChris Chubb
 
Portfolio Book Clubs
Portfolio   Book ClubsPortfolio   Book Clubs
Portfolio Book ClubsChris Chubb
 
Colocation Tradeoffs
Colocation TradeoffsColocation Tradeoffs
Colocation TradeoffsChris Chubb
 
Website Creation Process
Website Creation ProcessWebsite Creation Process
Website Creation ProcessChris Chubb
 
Virtual Company Tools
Virtual Company ToolsVirtual Company Tools
Virtual Company ToolsChris Chubb
 
Web 20 Checklist
Web 20 ChecklistWeb 20 Checklist
Web 20 ChecklistChris Chubb
 
New Stuff In Php 5.3
New Stuff In Php 5.3New Stuff In Php 5.3
New Stuff In Php 5.3Chris Chubb
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 TrainingChris Chubb
 

More from Chris Chubb (19)

Red beanphp orm presentation
Red beanphp orm presentationRed beanphp orm presentation
Red beanphp orm presentation
 
Portfolio Public Affairs Council
Portfolio   Public Affairs CouncilPortfolio   Public Affairs Council
Portfolio Public Affairs Council
 
Portfolio Pact Publications
Portfolio   Pact PublicationsPortfolio   Pact Publications
Portfolio Pact Publications
 
Portfolio Npf Web Site Donate
Portfolio   Npf Web Site DonatePortfolio   Npf Web Site Donate
Portfolio Npf Web Site Donate
 
Portfolio Usccb
Portfolio   UsccbPortfolio   Usccb
Portfolio Usccb
 
Portfolio Webposition
Portfolio   WebpositionPortfolio   Webposition
Portfolio Webposition
 
Portfolio Link Popularity Check
Portfolio   Link Popularity CheckPortfolio   Link Popularity Check
Portfolio Link Popularity Check
 
Portfolio Npf Ms Batch Loader
Portfolio   Npf Ms Batch LoaderPortfolio   Npf Ms Batch Loader
Portfolio Npf Ms Batch Loader
 
Portfolio Npf Buy Site
Portfolio   Npf Buy SitePortfolio   Npf Buy Site
Portfolio Npf Buy Site
 
Portfolio Naic
Portfolio   NaicPortfolio   Naic
Portfolio Naic
 
Portfolio Ccsse
Portfolio   CcssePortfolio   Ccsse
Portfolio Ccsse
 
Portfolio Book Clubs
Portfolio   Book ClubsPortfolio   Book Clubs
Portfolio Book Clubs
 
Database Web
Database WebDatabase Web
Database Web
 
Colocation Tradeoffs
Colocation TradeoffsColocation Tradeoffs
Colocation Tradeoffs
 
Website Creation Process
Website Creation ProcessWebsite Creation Process
Website Creation Process
 
Virtual Company Tools
Virtual Company ToolsVirtual Company Tools
Virtual Company Tools
 
Web 20 Checklist
Web 20 ChecklistWeb 20 Checklist
Web 20 Checklist
 
New Stuff In Php 5.3
New Stuff In Php 5.3New Stuff In Php 5.3
New Stuff In Php 5.3
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 Training
 

Recently uploaded

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

Php Chapter 2 3 Training

  • 1. PHP Functions and Arrays Orlando PHP Meetup Zend Certification Training March 2009
  • 2. Functions Minimal syntax function name() { } PHP function names are not case- sensitive. All functions in PHP return a value—even if you don’t explicitly cause them to. No explicit return value returns NULL “return $value;” exits function immediately.
  • 3. Variable Scope Global scope A variable declared or first used outside of a function or class has global scope. NOT visible inside functions by default. Use “global $varname;” to make a global variable visible inside a function. Function scope Declared or passed in via function parameters. A visible throughout the function, then discarded when the function exits. Case scope Stay tuned for Object Oriented chapter…
  • 4. Scope (continued) Global $a = "Hello"; $b = "World"; function hello() { global $a, $b; echo "$a $b"; echo $GLOBALS[’a’] .’ ’. $GLOBALS[’b’]; }
  • 5. Scope (continued) Regular Parameters function hello($who = "World") { echo "Hello $who"; } Variable Length Parameters func_num_args(), func_get_arg() and func_get_args() function hello() { if (func_num_args() > 0) { $arg = func_get_arg(0); // The first argument is at position 0 echo "Hello $arg"; } else { echo "Hello World"; }
  • 6. Passing Arguments by ReferencePrefix a parameter with an “&” Function func (&$variable) {} Changes to the variable will persist after the function call function cmdExists($cmd, &$output = null) { $output = ‘whereis $cmd‘; if (strpos($output, DIRECTORY_SEPARATOR) !== false) { return true; } else { return false; } }
  • 7. Function Summary Declare functions with parameters and return values By default, parameters and variables have function scope. Pass parameters by reference to return values to calling function. Parameters can have default values. If no default identified, then parameter must be passed in or an error will be thrown. Parameter arrays are powerful but hard to debug.
  • 8. Arrays All arrays are ordered collections of items, called elements. Has a value, identified by a unique key (integer or case sensitive string) Keys By default, keys start at zero String can be of any length Value can be any variable type (string, number, object, resource, etc.)
  • 9. Declaring Arrays Explicit $a = array (10, 20, 30); $a = array (’a’ => 10, ’b’ => 20, ’cee’ => 30); $a = array (5 => 1, 3 => 2, 1 => 3,); $a = array(); //Empty Implicit $x[] = 10; //Gets next available int index, 0 $x[] = 11; //Next index, 1 $x[’aa’] = 11;
  • 10. Printing Arrays print_r() Recursively prints the values May return value as a string to assign to a variable. Var_dump() outputs the data types of each value Can only echo immediately
  • 11. Enumerative vs. Associative Enumerative Integer indexes, assigned sequentially When no key given, next key = max(integer keys) + 1 Associative Integer or String keys, assigned specifically Keys are case sensitive but type insensitive ‘a’ != ‘A’ but ‘1’ == 1 Mixed $a = array (’4’ => 5, ’a’ => ’b’); $a[] = 44; // This will have a key of 5
  • 12. Multi-dimensional Arrays Array item value is another array $array = array(); $array[] = array(’foo’,’bar’); $array[] = array(’baz’,’bat’); echo $array[0][1] . $array[1] [0];
  • 13. Unraveling Arrays list() operator Receives the results of an array List($a, $b, $c) = array(‘one’, ‘two’, ‘three’); Assigns $a = ‘one’, $b = ‘two’, $c = ‘three’ Useful for functions that return an array list($first, $last, $last_login) = mysql_fetch_row($result);
  • 14. Comparing Arrays Equal (==) Arrays must have the same number and value of keys and values, but in any order Exactly Equal (===) Arrays must have the same number and value of keys and values and in the exact same order.
  • 15. Counting, Searching and Deleting Elements count($array) Returns the number of elements in the first level of the array. array_key_exists($key, $array) If array element with key exists, returns TRUE, even if value is NULL in_array($value, $array) If the value is in the array, returns TRUE unset($array[$key]) Removes the element from the array.
  • 16. Flipping and Reversing array_flip($array) Swaps keys for values Returns a new array array_reverse($array) Reverses the order of the key/value pairs Returns a new array Don’t confuse the two, like I usually do
  • 17. Array Iteration The Array Pointer reset(), end(), next(), prev(), current(), key() An Easier Way to Iterate foreach($array as $value) {} foreach($array as $key=>$value){} Walk the array and process each value array_walk($array, ‘function name to call’); array_walk_recursive($array, ‘function’);
  • 18. Sorting Arrays There are eleven sorting functions in PHP sort($array) Sorts the array in place and then returns. All keys become integers 0,1,2,… asort($array) Sorts the array in place and returns Sorts on values, but leaves key assignments in place. rsort() and arsort() to reverse sort. ksort() and krsort() to sort by key, not value
  • 19. Sorting (continued) usort($array, ‘compare_function’) Compare_function($one, $two) returns -1 if $one < $two 0 if $one == $two 1 if $one > $two Great if you are sorting on a special function, like length of the strings or age or something like that. uasort() to retain key=>value association. shuffle($array) is the anti-sort
  • 20. Arrays as Stacks, Queues and Sets Stacks (Last in, first out) array_push($array, $value [, $value2] ) $value = array_pop($array) Queue (First in, first out) array_unshift($array, $value [, $value2] ) $value = array_shift($array) Set Functionality $array = array_diff($array1, $array2) $array = array_intersect($a1, $a2)
  • 21. Summary Arrays are probably the single most powerful data management tool available to PHP developers. Therefore, learning to use them properly is essential for a good developer. Some methods are naturally more efficient than others. Read the function notes to help you decide. Look for ways in your code to use arrays to reduce code and improve flexibility.
  • 22. Thank You Shameless Plug 15 years of development experience, 14 of that running my own company. I am currently available for new contract work in PHP and .NET. cchubb@codegurus.com