SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 

Kürzlich hochgeladen (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 

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