SlideShare a Scribd company logo
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 1 © Wiley and the book authors, 2002
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 2 © Wiley and the book authors, 2002
Introduction to
PHP Arrays
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 3 © Wiley and the book authors, 2002
SummarySummary
• How arrays work in PHP
• Using multidimensional arrays
• Imitating other data structures with arrays
• Sorting and other transformations
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 4 © Wiley and the book authors, 2002
Uses of ArraysUses of Arrays
• Arrays are definitely one of the coolest and most flexible
features of PHP. Unlike vector arrays from other
languages (C, C++, etc.), PHP arrays can store data of
varied types and automatically organize it for you in a
large variety of ways.
• Some of the ways arrays are used in PHP include:
o Built-in PHP environment variables are in the form of arrays (e.g. $_POST)
o Most database functions transport their info via arrays, making a compact
package of an arbitrary chunk of data
o It's easy to pass entire sets of HTML form arguments from one page to another
in a single array
o Arrays make nice containers for doing manipulations (sorting, counting, etc.)
of any data you develop while executing a single page's script
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 5 © Wiley and the book authors, 2002
What are PHP arraysWhat are PHP arrays
• PHP arrays are associative arrays with a little extra thrown in.
• The associative part means that arrays store element values in
association with key values, rather than in a strict linear index
order
• If you store an element in an array, in association with a key,
all you need to retrieve it later from that array is the key value
o $state_location['San_Mateo'] = 'California';
o $state = $state_location['San_Mateo'];
• If you want to associate a numerical ordering with a bunch of
values or just store a list of values, all you have to do is use
integers as your key values
o $my_array[1] = 'The first thing';
o $my_array[2] = 'The second thing';
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 6 © Wiley and the book authors, 2002
Associative vs. vectorAssociative vs. vector
arraysarrays
• In vector arrays (like those used in C/C++), the contained
elements all need to be of the same type, and usually the
language compiler needs to know in advance how many
such elements there are likely to be
o double my_array[100]; // this is C
• Consequently, vector arrays are very fast for storage and
lookup since the program knows the exact location of each
element and they are stored in a contiguous block of memory
• PHP arrays are associative (and may be referred to as hashes)
• Rather than having a fixed number of slots, PHP creates array
slots as new elements are added to the array and elements
can be of any PHP type
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 7 © Wiley and the book authors, 2002
Creating arraysCreating arrays
• There are 4 main ways to create arrays in PHP
o Direct assignment
• Simply act as though a variable is already an array and assign a value into
it
$my_array[1] = 1001;
o The array() construct
• Creates a new array from the specification of its elements and associated
keys
• Can be called with no arguments to create an empty array (e.g. to pass
into functions which require an array argument)
• Can also pass in a comma-separated list of elements to be stored and the
indices will be automatically created beginning with 0
$fruit_basket = array('apple','orange','banana','pear');
o Where $fruit_basket[0] == 'apple', $fruit_basket[1] == 'orange', etc.
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 8 © Wiley and the book authors, 2002
Creating arrays (cont.)Creating arrays (cont.)
o Specifying indices using array()
• If you want to create arrays in the previous manner but specify the indices
used, instead of simply separating the values with commas, you supply
key-value pairs separated by commas where the key and the value are
separated by the special symbol =>
$fruit_basket = array ('red' => 'apple',
'orange' => 'orange',
'yellow' => 'banana',
'green' => 'pear');
o Functions returning arrays
• You can write your own function which returns an array or use one of the
built-in PHP functions which return an array and assign it to a variable
$my_array = range(6,10);
o Is equivalent to
$my_array = array(6,7,8,9,10);
o Where $my_array[0] == 6;
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 9 © Wiley and the book authors, 2002
Retrieving valuesRetrieving values
• The most direct way to retrieve a value is to use its
index
o If we have stored a value in $my_array at index 5, then $my_array[5] will
retrieve that value. If nothing had been stored at index 5 or if $my_array
had not been assigned, $my_array[5] will behave as an unbound variable
• The list() construct is used to assign several array
elements to variables in succession
$fruit_basket = array('apple','orange','banana');
list($red_fruit,$orange_fruit) = $fruit_basket;
o The variables in list() will be assigned the elements of the array in the
order they were originally stored in the array
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 10 © Wiley and the book authors, 2002
Multidimensional arraysMultidimensional arrays
• The arrays we have looked at so far are one-dimensional
in that they only require a single key for assigning or
retrieving values
• PHP can easily support multiple-dimensional arrays, with
arbitrary numbers of keys
o Just like one-dimensional arrays, there is no need to declare our intensions in
advance, you can just assign values to the index
$multi_array[1][2][3][4][5] = 'deep treasure';
• Which will create a five-dimensional array with successive keys that
happen, in this case, to be five successive integers
• It may be easier to consider that the values stored in
arrays can themselves be arrays.
$multi_level[0] = array(1,2,3,4,5);
• Where $multi_level[0][0] == 1 and $multi_level[0][1] == 2
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 11 © Wiley and the book authors, 2002
Multidimensional arraysMultidimensional arrays
(cont.)(cont.)
$cornucopia = array('fruit' => array('red' => 'apple',
'orange' => 'orange',
'yellow' => 'banana',
'green' => 'pear'),
'flower' => array('red' => 'rose',
'yellow' => 'sunflower',
'purple' => 'iris'));
$kind_wanted = 'flower';
$color_wanted = 'purple';
print("The $color_wanted $kind_wanted is {$cornucopia[$kind_wanted]
[$color_wanted]}");
• Would print the message "The purple flower is iris"
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 12 © Wiley and the book authors, 2002
Deleting from arraysDeleting from arrays
• Deleting an element from an array is just like getting
rid of an assigned variable calling the unset()
construct
unset($my_array[2]);
unset($my_other_array['yellow']);
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 13 © Wiley and the book authors, 2002
IterationIteration
• Iteration constructs provide techniques for dealing with
array elements in bulk by letting us step or loop through
arrays, element by element or key by key
• In addition to storing values in association with their keys,
PHP arrays silently build an ordered list of the key/value
pairs that are stored, in the order that they are stored for
operations that iterate over the entire contents of the
array
• Each array remembers a particular stored key/value pair
as being the current one, and array iteration functions
work in part by shifting that current marker through the
internal list of keys and values
o This is commonly referred to as the iteration pointer, although PHP does not
support full pointers in the sense that C/C++ programmers may be used to
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 14 © Wiley and the book authors, 2002
Our favorite iterationOur favorite iteration
method:method: foreachforeach• Our favorite construct for looping through an array is foreach which is
somewhat related to Perl's foreach, although it has a different syntax
• There are 2 flavors of the foreach statement
o foreach (array_expression as $value_var)
• loops over the array given by array_expression. On each loop, the value of the
current element is assigned to $value_var and the internal array pointer is
advanced by one (so on the next loop, you'll be looking at the next element)
o foreach (array_expression as $key_var => $value_var)
• does the same thing, except that the current element's key will be assigned to
the variable $key_var on each loop
• array_expression can be any expression which evaluates to an array
• When foreach first starts executing, the internal array pointer is automatically
reset to the first element of the array. This means that you do not need to call
reset() before a foreach loop
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 15 © Wiley and the book authors, 2002
foreachforeach exampleexample
• If you would like to see each of the variables names
and values sent to a PHP script via the POST
method, you can utilize the foreach construct to
loop through the $_POST array
print ('<TABLE><TR><TH>Name</TH>'.
'<TH>Value</TH></TR>');
foreach ($_POST as $input_name => $value)
{
print ("<TR><TH>$input_name</TH>".
"<TD>$value</TD></TR>n");
}
print ('</TABLE>');
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 16 © Wiley and the book authors, 2002
Iterating withIterating with current()current()
andand next()next()
• foreach is useful in situations where you want to simply loop through an array's values
• For more control, you can utilize current() and next()
• The current() function returns the stored value that the current array pointer is pointing
to
o When an array is newly created with elements, the element pointed to will always
be the first element added
• The next() function advances the array pointer and then returns the current value
pointed to
o If the pointer is already pointing to the last stored value, the function returns false
o If false is a value stored in the array, next will return false even if it has not reached
the end of the array
• To return the array pointer to the first element in the array, use the reset() function
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 17 © Wiley and the book authors, 2002
Reverse order withReverse order with end()end()
andand prev()prev()
• Analogous to reset() (which sets the array pointer to the
beginning of the array) and next() (which sets the array
pointer to the next element in the array and returns its value)
are end() and prev()
o end() moves the pointer to the last element in the array and returns its value
o prev() moves the pointer to the previous element in the array and returns its value
• Another function designed to work with iterating through
arrays is the key() function which returns the associated key
from the current array pointer
• Note: when passing an array to a function - just like other
variables - only a copy of the array is passed, not the original.
Subsequent modifications to the array's values or its pointer will be
lost once the function returns unless the array is passed by
reference
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 18 © Wiley and the book authors, 2002
Empty values and theEmpty values and the
each() functioneach() function
• One problem with utilizing the next function to determine when
the end of the array has been reached is if a false value or a
value which is evaluated to be false has been stored in the array
$my_array = array(1000,100,0,10,1);
print (current($my_array));
while ($current_value = next($my_array))
print ($current_value);
o Will stop executing when reaching the third element of the array
• The each() function is similar to next() except that it returns an
array of information instead of the value stored at the next
location in the loop. Additionally, the each() function returns the
information for where the pointer is currently located before
incrementing the pointer
o The each() function returns the following information in an array
• Key 0/'key': the current key at the array pointer
• Key 1/'value': the current value at the array pointer
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 19 © Wiley and the book authors, 2002
each()each() exampleexample
• To use each to iterate through the $_POST array:
print ('<TABLE><TR><TH>Name</TH>'.
'<TH>Value</TH></TR>');
reset ($_POST);
while ($current = each($_POST))
{
print ("<TR><TH>{$current['key']}</TH>".
"<TD>{$current['value']}</TD></TR>n");
}
print ('</TABLE>');
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 20 © Wiley and the book authors, 2002
Transformations of arraysTransformations of arrays
• PHP offers a host of functions for manipulating your data
once you have nicely stored it in an array
o The functions in this section have in common is that they take your array, do
something with it, and return the results in another array
• array array_keys (array input [,mixed search_value])
returns the keys, numeric and string, from the input array.
o If the optional search_value is specified, then only the keys for that value are
returned. Otherwise, all the keys from the input are returned.
• array array_values ( array input) returns all the values
from the input array and indexes numerically the array
o Simply returns the original array without the keys
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 21 © Wiley and the book authors, 2002
More arrayMore array transformationtransformation
functionsfunctions• array array_count_values ( array input) returns an array using the
values of the input array as keys and their frequency in input as values
o In other words, array_count_values takes an array as input and returns
a new array where the values from the original array are the keys for the
new array and the values are the number of times each old value
occurred in the original array
• array array_flip ( array trans) returns an array in flip order, i.e. keys
from trans become values and values from trans become keys
o Although array keys are guaranteed to be unique, array values are not.
Consequently, any duplicate values in the original array become the
same key in the new array (only the latest of the original keys will survive to
become the new values)
o The array values also have to be integers or strings. If values which cannot
be converted to keys are encountered, the function will fail and a
warning will be issues
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 22 © Wiley and the book authors, 2002
More arrayMore array transformationtransformation
functionsfunctions• array array_reverse ( array array [, bool preserve_keys])
takes input array and returns a new array with the order of the elements
reversed, preserving the keys if preserve_keys is TRUE
• void shuffle ( array array) shuffles (randomizes the order of the
elements in) an array
o Note: calls to srand prior to shuffle is no longer necessary
o Unlike most functions, shuffle actually modifies the original array
and does not return a value
• array array_merge ( array array1, array array2 [,
array ...]) merges the elements of two or more arrays together so
that the values of one are appended to the end of the previous one. It
returns the resulting array
o If the input arrays have the same string keys, then the later value for
that key will overwrite the previous one. If, however, the arrays
contain numeric keys, the later value will not overwrite the original
value, but will be appended
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 23 © Wiley and the book authors, 2002
SortingSorting
• PHP offers a host of functions for sorting arrays
o As we saw earlier, a tension sometimes arises between respecting the
key/value associations in an array and treating numerical keys as
ordering info that should be changed when the order changes
o PHP offers variants of the sorting functions for each of these behaviors
and also allows sorting in ascending or descending order and by
user-supplied ordering functions
• Conventions used in naming the sorting functions include:
o An initial a means that the function sorts by value but maintains the
association between key/value pairs the way it was
o An initial k means that it sorts by key but maintains the key/value
associations
o A lack of an initial a or k means that it sorts by value but doesn’t
maintain the key/value association (e.g. numerical keys will be
renumbered to reflect the new ordering
o An r before the sort means that the sorting order will be reversed
o An initial u means that a second argument is expected: the name of
a user-defined function that specifies the ordering of any two
elements that are being sorted
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 24 © Wiley and the book authors, 2002
Printing functions forPrinting functions for
arrays (debugging)arrays (debugging)
• bool print_r ( mixed expression [, bool return]) displays information about a
variable in a way that's readable by humans. If given a string, integer or float,
the value itself will be printed. If given an array, values will be presented in a
format that shows keys and elements. Similar notation is used for objects.
print_r() and var_export() will also show protected and private properties of
objects with PHP 5, on the contrary to var_dump().
o Remember that print_r() will move the array pointer to the end. Use reset()
to bring it back to beginning
_______________________________________________________________________________________________________________
PHP Bible, 2nd
Edition 25 © Wiley and the book authors, 2002
ThankThank You !!!You !!!
For More Information click below link:
Follow Us on:
http://vibranttechnologies.co.in/php-classes-in-mumbai.html

More Related Content

Similar to PHP - Introduction to PHP Arrays (20)

CA Database Scavenger Hunt pt. 1
CA Database Scavenger Hunt pt. 1CA Database Scavenger Hunt pt. 1
CA Database Scavenger Hunt pt. 1
amytaylor
 
8.4 guided notes
8.4 guided notes8.4 guided notes
8.4 guided notes
leblance
 
Rri framework
Rri frameworkRri framework
Rri framework
gnonewleaders
 
Pc8-2 Vectors2 Notes
Pc8-2 Vectors2 NotesPc8-2 Vectors2 Notes
Pc8-2 Vectors2 Notes
vhiggins1
 
computer science file (python)
computer science file (python)computer science file (python)
computer science file (python)
aashish kumar
 
Chapter 12 Definitions
Chapter 12 DefinitionsChapter 12 Definitions
Chapter 12 Definitions
guestea255c
 
8.2 critical region guided notes
8.2 critical region guided notes8.2 critical region guided notes
8.2 critical region guided notes
leblance
 
Definitions chpt.9
Definitions chpt.9Definitions chpt.9
Definitions chpt.9
guestea255c
 
Chapter 9 Definitions
Chapter 9 DefinitionsChapter 9 Definitions
Chapter 9 Definitions
guest8e31754
 
Chapter 9 Definitions
Chapter 9 DefinitionsChapter 9 Definitions
Chapter 9 Definitions
guest09de1
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guest39185e
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guestdf7154
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guest1c0362
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guest2d446e
 
Chapter 9 Definitions
Chapter 9 DefinitionsChapter 9 Definitions
Chapter 9 Definitions
guest80e6de
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guest777c6c
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guest4182da0
 
Data Vault: What is it? Where does it fit? SQL Saturday #249
Data Vault: What is it?  Where does it fit?  SQL Saturday #249Data Vault: What is it?  Where does it fit?  SQL Saturday #249
Data Vault: What is it? Where does it fit? SQL Saturday #249
Daniel Upton
 
2 book report spring 2013
2 book report spring 20132 book report spring 2013
2 book report spring 2013
Meagan Kaiser
 
Lab 06 db
Lab 06 dbLab 06 db
Lab 06 db
Ashwin Kumar
 
CA Database Scavenger Hunt pt. 1
CA Database Scavenger Hunt pt. 1CA Database Scavenger Hunt pt. 1
CA Database Scavenger Hunt pt. 1
amytaylor
 
8.4 guided notes
8.4 guided notes8.4 guided notes
8.4 guided notes
leblance
 
Pc8-2 Vectors2 Notes
Pc8-2 Vectors2 NotesPc8-2 Vectors2 Notes
Pc8-2 Vectors2 Notes
vhiggins1
 
computer science file (python)
computer science file (python)computer science file (python)
computer science file (python)
aashish kumar
 
Chapter 12 Definitions
Chapter 12 DefinitionsChapter 12 Definitions
Chapter 12 Definitions
guestea255c
 
8.2 critical region guided notes
8.2 critical region guided notes8.2 critical region guided notes
8.2 critical region guided notes
leblance
 
Definitions chpt.9
Definitions chpt.9Definitions chpt.9
Definitions chpt.9
guestea255c
 
Chapter 9 Definitions
Chapter 9 DefinitionsChapter 9 Definitions
Chapter 9 Definitions
guest8e31754
 
Chapter 9 Definitions
Chapter 9 DefinitionsChapter 9 Definitions
Chapter 9 Definitions
guest09de1
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guest39185e
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guestdf7154
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guest1c0362
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guest2d446e
 
Chapter 9 Definitions
Chapter 9 DefinitionsChapter 9 Definitions
Chapter 9 Definitions
guest80e6de
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guest777c6c
 
Chpater 9 Definitions
Chpater 9 DefinitionsChpater 9 Definitions
Chpater 9 Definitions
guest4182da0
 
Data Vault: What is it? Where does it fit? SQL Saturday #249
Data Vault: What is it?  Where does it fit?  SQL Saturday #249Data Vault: What is it?  Where does it fit?  SQL Saturday #249
Data Vault: What is it? Where does it fit? SQL Saturday #249
Daniel Upton
 
2 book report spring 2013
2 book report spring 20132 book report spring 2013
2 book report spring 2013
Meagan Kaiser
 

More from Vibrant Technologies & Computers (20)

Buisness analyst business analysis overview ppt 5
Buisness analyst business analysis overview ppt 5Buisness analyst business analysis overview ppt 5
Buisness analyst business analysis overview ppt 5
Vibrant Technologies & Computers
 
SQL Introduction to displaying data from multiple tables
SQL Introduction to displaying data from multiple tables  SQL Introduction to displaying data from multiple tables
SQL Introduction to displaying data from multiple tables
Vibrant Technologies & Computers
 
SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
Vibrant Technologies & Computers
 
SQL- Introduction to SQL database
SQL- Introduction to SQL database SQL- Introduction to SQL database
SQL- Introduction to SQL database
Vibrant Technologies & Computers
 
ITIL - introduction to ITIL
ITIL - introduction to ITILITIL - introduction to ITIL
ITIL - introduction to ITIL
Vibrant Technologies & Computers
 
Salesforce - Introduction to Security & Access
Salesforce -  Introduction to Security & Access Salesforce -  Introduction to Security & Access
Salesforce - Introduction to Security & Access
Vibrant Technologies & Computers
 
Data ware housing- Introduction to olap .
Data ware housing- Introduction to  olap .Data ware housing- Introduction to  olap .
Data ware housing- Introduction to olap .
Vibrant Technologies & Computers
 
Data ware housing - Introduction to data ware housing process.
Data ware housing - Introduction to data ware housing process.Data ware housing - Introduction to data ware housing process.
Data ware housing - Introduction to data ware housing process.
Vibrant Technologies & Computers
 
Data ware housing- Introduction to data ware housing
Data ware housing- Introduction to data ware housingData ware housing- Introduction to data ware housing
Data ware housing- Introduction to data ware housing
Vibrant Technologies & Computers
 
Salesforce - classification of cloud computing
Salesforce - classification of cloud computingSalesforce - classification of cloud computing
Salesforce - classification of cloud computing
Vibrant Technologies & Computers
 
Salesforce - cloud computing fundamental
Salesforce - cloud computing fundamentalSalesforce - cloud computing fundamental
Salesforce - cloud computing fundamental
Vibrant Technologies & Computers
 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
Vibrant Technologies & Computers
 
SQL- Introduction to advanced sql concepts
SQL- Introduction to  advanced sql conceptsSQL- Introduction to  advanced sql concepts
SQL- Introduction to advanced sql concepts
Vibrant Technologies & Computers
 
SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data   SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data
Vibrant Technologies & Computers
 
SQL- Introduction to SQL Set Operations
SQL- Introduction to SQL Set OperationsSQL- Introduction to SQL Set Operations
SQL- Introduction to SQL Set Operations
Vibrant Technologies & Computers
 
Sas - Introduction to designing the data mart
Sas - Introduction to designing the data martSas - Introduction to designing the data mart
Sas - Introduction to designing the data mart
Vibrant Technologies & Computers
 
Sas - Introduction to working under change management
Sas - Introduction to working under change managementSas - Introduction to working under change management
Sas - Introduction to working under change management
Vibrant Technologies & Computers
 
SAS - overview of SAS
SAS - overview of SASSAS - overview of SAS
SAS - overview of SAS
Vibrant Technologies & Computers
 
Teradata - Architecture of Teradata
Teradata - Architecture of TeradataTeradata - Architecture of Teradata
Teradata - Architecture of Teradata
Vibrant Technologies & Computers
 
Teradata - Restoring Data
Teradata - Restoring Data Teradata - Restoring Data
Teradata - Restoring Data
Vibrant Technologies & Computers
 
Data ware housing - Introduction to data ware housing process.
Data ware housing - Introduction to data ware housing process.Data ware housing - Introduction to data ware housing process.
Data ware housing - Introduction to data ware housing process.
Vibrant Technologies & Computers
 
Ad

Recently uploaded (20)

How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Ad

PHP - Introduction to PHP Arrays

  • 3. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 3 © Wiley and the book authors, 2002 SummarySummary • How arrays work in PHP • Using multidimensional arrays • Imitating other data structures with arrays • Sorting and other transformations
  • 4. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 4 © Wiley and the book authors, 2002 Uses of ArraysUses of Arrays • Arrays are definitely one of the coolest and most flexible features of PHP. Unlike vector arrays from other languages (C, C++, etc.), PHP arrays can store data of varied types and automatically organize it for you in a large variety of ways. • Some of the ways arrays are used in PHP include: o Built-in PHP environment variables are in the form of arrays (e.g. $_POST) o Most database functions transport their info via arrays, making a compact package of an arbitrary chunk of data o It's easy to pass entire sets of HTML form arguments from one page to another in a single array o Arrays make nice containers for doing manipulations (sorting, counting, etc.) of any data you develop while executing a single page's script
  • 5. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 5 © Wiley and the book authors, 2002 What are PHP arraysWhat are PHP arrays • PHP arrays are associative arrays with a little extra thrown in. • The associative part means that arrays store element values in association with key values, rather than in a strict linear index order • If you store an element in an array, in association with a key, all you need to retrieve it later from that array is the key value o $state_location['San_Mateo'] = 'California'; o $state = $state_location['San_Mateo']; • If you want to associate a numerical ordering with a bunch of values or just store a list of values, all you have to do is use integers as your key values o $my_array[1] = 'The first thing'; o $my_array[2] = 'The second thing';
  • 6. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 6 © Wiley and the book authors, 2002 Associative vs. vectorAssociative vs. vector arraysarrays • In vector arrays (like those used in C/C++), the contained elements all need to be of the same type, and usually the language compiler needs to know in advance how many such elements there are likely to be o double my_array[100]; // this is C • Consequently, vector arrays are very fast for storage and lookup since the program knows the exact location of each element and they are stored in a contiguous block of memory • PHP arrays are associative (and may be referred to as hashes) • Rather than having a fixed number of slots, PHP creates array slots as new elements are added to the array and elements can be of any PHP type
  • 7. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 7 © Wiley and the book authors, 2002 Creating arraysCreating arrays • There are 4 main ways to create arrays in PHP o Direct assignment • Simply act as though a variable is already an array and assign a value into it $my_array[1] = 1001; o The array() construct • Creates a new array from the specification of its elements and associated keys • Can be called with no arguments to create an empty array (e.g. to pass into functions which require an array argument) • Can also pass in a comma-separated list of elements to be stored and the indices will be automatically created beginning with 0 $fruit_basket = array('apple','orange','banana','pear'); o Where $fruit_basket[0] == 'apple', $fruit_basket[1] == 'orange', etc.
  • 8. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 8 © Wiley and the book authors, 2002 Creating arrays (cont.)Creating arrays (cont.) o Specifying indices using array() • If you want to create arrays in the previous manner but specify the indices used, instead of simply separating the values with commas, you supply key-value pairs separated by commas where the key and the value are separated by the special symbol => $fruit_basket = array ('red' => 'apple', 'orange' => 'orange', 'yellow' => 'banana', 'green' => 'pear'); o Functions returning arrays • You can write your own function which returns an array or use one of the built-in PHP functions which return an array and assign it to a variable $my_array = range(6,10); o Is equivalent to $my_array = array(6,7,8,9,10); o Where $my_array[0] == 6;
  • 9. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 9 © Wiley and the book authors, 2002 Retrieving valuesRetrieving values • The most direct way to retrieve a value is to use its index o If we have stored a value in $my_array at index 5, then $my_array[5] will retrieve that value. If nothing had been stored at index 5 or if $my_array had not been assigned, $my_array[5] will behave as an unbound variable • The list() construct is used to assign several array elements to variables in succession $fruit_basket = array('apple','orange','banana'); list($red_fruit,$orange_fruit) = $fruit_basket; o The variables in list() will be assigned the elements of the array in the order they were originally stored in the array
  • 10. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 10 © Wiley and the book authors, 2002 Multidimensional arraysMultidimensional arrays • The arrays we have looked at so far are one-dimensional in that they only require a single key for assigning or retrieving values • PHP can easily support multiple-dimensional arrays, with arbitrary numbers of keys o Just like one-dimensional arrays, there is no need to declare our intensions in advance, you can just assign values to the index $multi_array[1][2][3][4][5] = 'deep treasure'; • Which will create a five-dimensional array with successive keys that happen, in this case, to be five successive integers • It may be easier to consider that the values stored in arrays can themselves be arrays. $multi_level[0] = array(1,2,3,4,5); • Where $multi_level[0][0] == 1 and $multi_level[0][1] == 2
  • 11. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 11 © Wiley and the book authors, 2002 Multidimensional arraysMultidimensional arrays (cont.)(cont.) $cornucopia = array('fruit' => array('red' => 'apple', 'orange' => 'orange', 'yellow' => 'banana', 'green' => 'pear'), 'flower' => array('red' => 'rose', 'yellow' => 'sunflower', 'purple' => 'iris')); $kind_wanted = 'flower'; $color_wanted = 'purple'; print("The $color_wanted $kind_wanted is {$cornucopia[$kind_wanted] [$color_wanted]}"); • Would print the message "The purple flower is iris"
  • 12. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 12 © Wiley and the book authors, 2002 Deleting from arraysDeleting from arrays • Deleting an element from an array is just like getting rid of an assigned variable calling the unset() construct unset($my_array[2]); unset($my_other_array['yellow']);
  • 13. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 13 © Wiley and the book authors, 2002 IterationIteration • Iteration constructs provide techniques for dealing with array elements in bulk by letting us step or loop through arrays, element by element or key by key • In addition to storing values in association with their keys, PHP arrays silently build an ordered list of the key/value pairs that are stored, in the order that they are stored for operations that iterate over the entire contents of the array • Each array remembers a particular stored key/value pair as being the current one, and array iteration functions work in part by shifting that current marker through the internal list of keys and values o This is commonly referred to as the iteration pointer, although PHP does not support full pointers in the sense that C/C++ programmers may be used to
  • 14. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 14 © Wiley and the book authors, 2002 Our favorite iterationOur favorite iteration method:method: foreachforeach• Our favorite construct for looping through an array is foreach which is somewhat related to Perl's foreach, although it has a different syntax • There are 2 flavors of the foreach statement o foreach (array_expression as $value_var) • loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value_var and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element) o foreach (array_expression as $key_var => $value_var) • does the same thing, except that the current element's key will be assigned to the variable $key_var on each loop • array_expression can be any expression which evaluates to an array • When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop
  • 15. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 15 © Wiley and the book authors, 2002 foreachforeach exampleexample • If you would like to see each of the variables names and values sent to a PHP script via the POST method, you can utilize the foreach construct to loop through the $_POST array print ('<TABLE><TR><TH>Name</TH>'. '<TH>Value</TH></TR>'); foreach ($_POST as $input_name => $value) { print ("<TR><TH>$input_name</TH>". "<TD>$value</TD></TR>n"); } print ('</TABLE>');
  • 16. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 16 © Wiley and the book authors, 2002 Iterating withIterating with current()current() andand next()next() • foreach is useful in situations where you want to simply loop through an array's values • For more control, you can utilize current() and next() • The current() function returns the stored value that the current array pointer is pointing to o When an array is newly created with elements, the element pointed to will always be the first element added • The next() function advances the array pointer and then returns the current value pointed to o If the pointer is already pointing to the last stored value, the function returns false o If false is a value stored in the array, next will return false even if it has not reached the end of the array • To return the array pointer to the first element in the array, use the reset() function
  • 17. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 17 © Wiley and the book authors, 2002 Reverse order withReverse order with end()end() andand prev()prev() • Analogous to reset() (which sets the array pointer to the beginning of the array) and next() (which sets the array pointer to the next element in the array and returns its value) are end() and prev() o end() moves the pointer to the last element in the array and returns its value o prev() moves the pointer to the previous element in the array and returns its value • Another function designed to work with iterating through arrays is the key() function which returns the associated key from the current array pointer • Note: when passing an array to a function - just like other variables - only a copy of the array is passed, not the original. Subsequent modifications to the array's values or its pointer will be lost once the function returns unless the array is passed by reference
  • 18. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 18 © Wiley and the book authors, 2002 Empty values and theEmpty values and the each() functioneach() function • One problem with utilizing the next function to determine when the end of the array has been reached is if a false value or a value which is evaluated to be false has been stored in the array $my_array = array(1000,100,0,10,1); print (current($my_array)); while ($current_value = next($my_array)) print ($current_value); o Will stop executing when reaching the third element of the array • The each() function is similar to next() except that it returns an array of information instead of the value stored at the next location in the loop. Additionally, the each() function returns the information for where the pointer is currently located before incrementing the pointer o The each() function returns the following information in an array • Key 0/'key': the current key at the array pointer • Key 1/'value': the current value at the array pointer
  • 19. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 19 © Wiley and the book authors, 2002 each()each() exampleexample • To use each to iterate through the $_POST array: print ('<TABLE><TR><TH>Name</TH>'. '<TH>Value</TH></TR>'); reset ($_POST); while ($current = each($_POST)) { print ("<TR><TH>{$current['key']}</TH>". "<TD>{$current['value']}</TD></TR>n"); } print ('</TABLE>');
  • 20. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 20 © Wiley and the book authors, 2002 Transformations of arraysTransformations of arrays • PHP offers a host of functions for manipulating your data once you have nicely stored it in an array o The functions in this section have in common is that they take your array, do something with it, and return the results in another array • array array_keys (array input [,mixed search_value]) returns the keys, numeric and string, from the input array. o If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned. • array array_values ( array input) returns all the values from the input array and indexes numerically the array o Simply returns the original array without the keys
  • 21. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 21 © Wiley and the book authors, 2002 More arrayMore array transformationtransformation functionsfunctions• array array_count_values ( array input) returns an array using the values of the input array as keys and their frequency in input as values o In other words, array_count_values takes an array as input and returns a new array where the values from the original array are the keys for the new array and the values are the number of times each old value occurred in the original array • array array_flip ( array trans) returns an array in flip order, i.e. keys from trans become values and values from trans become keys o Although array keys are guaranteed to be unique, array values are not. Consequently, any duplicate values in the original array become the same key in the new array (only the latest of the original keys will survive to become the new values) o The array values also have to be integers or strings. If values which cannot be converted to keys are encountered, the function will fail and a warning will be issues
  • 22. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 22 © Wiley and the book authors, 2002 More arrayMore array transformationtransformation functionsfunctions• array array_reverse ( array array [, bool preserve_keys]) takes input array and returns a new array with the order of the elements reversed, preserving the keys if preserve_keys is TRUE • void shuffle ( array array) shuffles (randomizes the order of the elements in) an array o Note: calls to srand prior to shuffle is no longer necessary o Unlike most functions, shuffle actually modifies the original array and does not return a value • array array_merge ( array array1, array array2 [, array ...]) merges the elements of two or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array o If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended
  • 23. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 23 © Wiley and the book authors, 2002 SortingSorting • PHP offers a host of functions for sorting arrays o As we saw earlier, a tension sometimes arises between respecting the key/value associations in an array and treating numerical keys as ordering info that should be changed when the order changes o PHP offers variants of the sorting functions for each of these behaviors and also allows sorting in ascending or descending order and by user-supplied ordering functions • Conventions used in naming the sorting functions include: o An initial a means that the function sorts by value but maintains the association between key/value pairs the way it was o An initial k means that it sorts by key but maintains the key/value associations o A lack of an initial a or k means that it sorts by value but doesn’t maintain the key/value association (e.g. numerical keys will be renumbered to reflect the new ordering o An r before the sort means that the sorting order will be reversed o An initial u means that a second argument is expected: the name of a user-defined function that specifies the ordering of any two elements that are being sorted
  • 24. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 24 © Wiley and the book authors, 2002 Printing functions forPrinting functions for arrays (debugging)arrays (debugging) • bool print_r ( mixed expression [, bool return]) displays information about a variable in a way that's readable by humans. If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects. print_r() and var_export() will also show protected and private properties of objects with PHP 5, on the contrary to var_dump(). o Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning
  • 25. _______________________________________________________________________________________________________________ PHP Bible, 2nd Edition 25 © Wiley and the book authors, 2002 ThankThank You !!!You !!! For More Information click below link: Follow Us on: http://vibranttechnologies.co.in/php-classes-in-mumbai.html