SlideShare a Scribd company logo
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

PDF
PHP Unit 3 functions_in_php_2
PDF
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
PPT
Functions in php
PPT
Class 3 - PHP Functions
PPTX
Introduction in php
PPTX
Introduction in php part 2
PPTX
Object-Oriented Programming with PHP (part 1)
PPT
php 2 Function creating, calling, PHP built-in function
PHP Unit 3 functions_in_php_2
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Functions in php
Class 3 - PHP Functions
Introduction in php
Introduction in php part 2
Object-Oriented Programming with PHP (part 1)
php 2 Function creating, calling, PHP built-in function

What's hot (20)

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

Similar to Php Chapter 2 3 Training (20)

PPTX
PHP Functions & Arrays
PPT
Php my sql - functions - arrays - tutorial - programmerblog.net
PPTX
Chapter 2 wbp.pptx
PPTX
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
PDF
php AND MYSQL _ppt.pdf
PPT
Arrays in php
PPSX
DIWE - Advanced PHP Concepts
PPTX
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
PPTX
UNIT IV (4).pptx
PPT
PHP Workshop Notes
PDF
PHP-Cheat-Sheet.pdf
PPTX
PHP FUNCTIONS AND ARRAY.pptx
PPTX
Introduction to PHP_ Lexical structure_Array_Function_String
PPT
Introduction To Php For Wit2009
PPTX
unit 1.pptx
PDF
Hsc IT 5. Server-Side Scripting (PHP).pdf
PPT
Php Lecture Notes
PHP Functions & Arrays
Php my sql - functions - arrays - tutorial - programmerblog.net
Chapter 2 wbp.pptx
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
php AND MYSQL _ppt.pdf
Arrays in php
DIWE - Advanced PHP Concepts
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
UNIT IV (4).pptx
PHP Workshop Notes
PHP-Cheat-Sheet.pdf
PHP FUNCTIONS AND ARRAY.pptx
Introduction to PHP_ Lexical structure_Array_Function_String
Introduction To Php For Wit2009
unit 1.pptx
Hsc IT 5. Server-Side Scripting (PHP).pdf
Php Lecture Notes
Ad

More from Chris Chubb (19)

ODP
Red beanphp orm presentation
PDF
Portfolio Public Affairs Council
PDF
Portfolio Pact Publications
PDF
Portfolio Npf Web Site Donate
PDF
Portfolio Usccb
PDF
Portfolio Webposition
PDF
Portfolio Link Popularity Check
PDF
Portfolio Npf Ms Batch Loader
PDF
Portfolio Npf Buy Site
PDF
Portfolio Naic
PDF
Portfolio Ccsse
PDF
Portfolio Book Clubs
PPT
Database Web
PPT
Colocation Tradeoffs
PPT
Website Creation Process
PPT
Virtual Company Tools
ODT
Web 20 Checklist
ODP
New Stuff In Php 5.3
PPT
Php Chapter 4 Training
Red beanphp orm presentation
Portfolio Public Affairs Council
Portfolio Pact Publications
Portfolio Npf Web Site Donate
Portfolio Usccb
Portfolio Webposition
Portfolio Link Popularity Check
Portfolio Npf Ms Batch Loader
Portfolio Npf Buy Site
Portfolio Naic
Portfolio Ccsse
Portfolio Book Clubs
Database Web
Colocation Tradeoffs
Website Creation Process
Virtual Company Tools
Web 20 Checklist
New Stuff In Php 5.3
Php Chapter 4 Training

Recently uploaded (20)

PDF
Electronic commerce courselecture one. Pdf
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Cloud computing and distributed systems.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
KodekX | Application Modernization Development
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
Teaching material agriculture food technology
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Spectral efficient network and resource selection model in 5G networks
Electronic commerce courselecture one. Pdf
sap open course for s4hana steps from ECC to s4
Programs and apps: productivity, graphics, security and other tools
Cloud computing and distributed systems.
20250228 LYD VKU AI Blended-Learning.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Encapsulation theory and applications.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Dropbox Q2 2025 Financial Results & Investor Presentation
KodekX | Application Modernization Development
The Rise and Fall of 3GPP – Time for a Sabbatical?
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Empathic Computing: Creating Shared Understanding
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Machine learning based COVID-19 study performance prediction
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Teaching material agriculture food technology
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Spectral efficient network and resource selection model in 5G networks

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