Tải bản đầy đủ - 0 (trang)
Chapter 3. Arrays, Strings, and Advanced Data Manipulation in PHP

Chapter 3. Arrays, Strings, and Advanced Data Manipulation in PHP

Tải bản đầy đủ - 0trang

3.1Arrays

Programmerscontinuallyhavetodealwithcollectionsofdata

items.Forinstance,whenyouqueryadatabaseforproducts,

youmaygetacollectionwithmultipleresults.InPHP,aswith

manyprogramminglanguages,youcanhandletheseresults

throughanarray.Anarraycanbeconsideredanamethat

referstomanyrelateditems.

ArraysinPHParesophisticatedandmoreflexiblethaninmany

otherhigh-levellanguages.APHParrayisanorderedsetof

variables,inwhicheachvariablecalledanelementhasan

associatedkey.PHPallowselementstobeaccessedusing

eitherstringorintegerkeysPHPautomaticallyassignsinteger

keyvaluesifkeysarenotspecifiedwhenarraysare

constructed.

Arrayscanholdscalarvalues(integers,Booleans,strings,or

floats)orcompoundvalues(objectsandevenotherarrays).

Thesamearraycanevenholdelementsofdifferenttypes.In

thissection,weshowhowarraysareconstructedandintroduce

severalusefularrayfunctionsfromthePHPlibrary.



3.1.1CreatingArrays

PHPprovidesthearray()languageconstructthatcreates

arrays.Thefollowingexamplesshowhowarraysofintegersand

stringscanbeconstructedandassignedtovariablesforlater

use:

$numbers=array(5,4,3,2,1);

$words=array("Web","Database","Applications");



//Printthethirdelementfromthearrayofintegers:3

print$numbers[2];



//Printthefirstelementfromthearrayofstrings:"Web"

print$words[0];



Bycreatingarraysthisway,PHPassignsintegerkeys,or

indexestoeachelement.Bydefault,theindexforthefirst

elementinanarrayis0thismayseemoddbutthinkofthe

indexasanoffsetfromthestartingpositioninanarray.The

valuescontainedinanarraycanberetrievedandmodified

usingthebracket[]syntax.Youcanalsocreateanarrayby

assigningelementstoanew,unsetvariable.Thefollowingcode

fragmentillustratesthebracketsyntaxwithanarrayofstrings:

$newArray[0]="Potatoes";

$newArray[1]="Carrots";

$newArray[2]="Spinach";



//Replacethethirdelement

$newArray[2]="Tomatoes";



Inthisexample,PHPautomaticallytreats$newArrayasan

arraywithoutacalltoarray().

Anemptyarraycanbecreatedbyassigningtoavariablethe

returnvalueofarray().Valuescanthenbeaddedusingthe

bracketsyntax.PHPautomaticallyassignsthenextnumeric

indexasthekey(thelargestintegerkeyvalueplusone)when

akeyisn'tsupplied.Theresultofthefollowingfragmentisan

arraycontainingthreeitems.

$shopping=array();



$shopping[]="Milk";

$shopping[]="Coffee";

$shopping[]="Sugar";



It'salsoeasytoprintindividualelementvaluesthemselves:

print$shopping[0];//prints"Milk"

print$shopping[1];//prints"Coffee"

print$shopping[2];//prints"Sugar"



Whenprintingarrayelementsindouble-quotedstrings,you

needtousethebracessyntaxintroducedinChapter2,for

example:

//prints"ThefirstiteminmylistisMilk"



print"Thefirstiteminmylistis{$shopping[0]}";



Youcanalsoprintouttheentirecontentsofanarrayusingthe

print_r()functionthatweintroducedinChapter2.Passingthe

variable$shoppingfromthepreviousexampletoprint_r():

print_r($shopping);



printstheentirearrayshowingeachelementandassociated

index:

Array

(

[0]=>Milk

[1]=>Coffee

[2]=>Sugar

)



Toincludingprint_r()outputaspartofawebpage,youshould

use
tagstopreservetheformatting,otherwisetheoutput

isrenderedononelinebecauseoneormoreconsecutivewhite

spacecharactersistreatedasasinglespaceinHTML.Generally

youshouldavoidtheuseofthe
taginyourHTMLoutput,

howeverpreservingtheprint_r()formatmakesdebugging

mucheasier.Here'showyoucanusethe
tags:











Whiletheprint_r()functionisreallyonlyintendedfor

debuggingpurposes,andtheuseof
elementsinHTMLis

discouraged,weusetheprint_r()functionextensivelyinthis

chaptertohelpillustrateourexamples.



3.1.1.1Associativearrays

Anassociativearrayusesstringkeystoaccessvaluesstoredin

thearray.Anassociativearraycanbeconstructedwitharray()

byassociatingeachkeytoavalueusingthe=>operatoras

showninthefollowingexample:

$array=array("first"=>1,"second"=>2,"third"=>3);



//Printoutthesecondelement:prints"2"

print$array["second"];



Thesamearrayofintegerscanalsobecreatedwiththebracket

syntax:

$array["first"]=1;

$array["second"]=2;



$array["third"]=3;



The=>operatorcanalsobeusedtocreatenumericallyindexed

arraysthatstartatanyindexvalue.Oftenit'sconvenientto

startanarrayatindex1,asshowninthefollowingexample:

$numbers=array(1=>"one","two","three","four");



Arrayscanalsobecreatedwhereeachnumerickeyisspecified,

suchas:

$oddNumbers=array(1=>"one",3=>"three",5=>"five");



AllarraysinPHPareassociativewithelementsaccessedeither

byastringkeyoranintegerkey.Youcancreatearraysthatuse

bothintegerandstringkeys,howeversucharraysadd

complexitytoanapplicationandshouldbeavoided.Associative

arraysarecommoninotherlanguagesandaresometimes

calledhasharraysorhashtablesareferencetohowthearrayis

implemented.



3.1.1.2Removingelementsfromanarray

Anelementcanberemovedfromanarray,oranentirearray

canbedeleted,bycallingunset().However,removingan

elementdoesn'treassigntheindexesasthefollowingexample

shows:

$favorites=array("PHP","Ace","COBOL","Java","C++");



//removeCOBOLfromthearray

unset($favorites[2]);

print_r($favorites);



Initially,eachelementisassignedanumerickeystartingfrom

zero,andafterremovinganelement,thescriptprints:

Array([0]=>PHP[1]=>Ace[3]=>Java[4]=>C++)



Thereisnolongeranelementdefinedforindex2.Thisexample

illustratestheassociativenatureofallPHParrays:afteravalue

isaddedtoanarray,theassociatedkeyremainsunchanged

unlikeatrueindexthatwouldadjustwhenanarraychanges.

Todestroyawholearray,callunset()onthearrayvariable:

//destroythewholearray

unset($favorites);



3.1.1.3Arrayorder

Arrayspreservetheorderoftheelementsthattheycontain,

andnewelementsareappendedtotheendofanexistingarray.

Thefollowingfragmentcreatesanarrayspecifyingtheinteger



indexes1,3,and5;thenaddsvalueswiththeindexvalues2,

4,and6.

$numbers=array(1=>"one",3=>"three",5=>"five");



$numbers[2]="two";

$numbers[4]="four";

$numbers[6]="six";



print_r($numbers);



Theresultingorderisshownwhenthearraycontentsare

viewedwithprint_r():

Array

(

[1]=>one

[3]=>three

[5]=>five

[2]=>two

[4]=>four

[6]=>six



)



3.1.1.4Heterogeneousarrays

ThevaluesthatcanbestoredinasinglePHParraydon'thave

tobeofthesametype;PHParrayscancontainheterogeneous

valuesthatisanymixofinteger,string,Boolean,float,object,

andevenarrayvariables.Thefollowingexampleshowsthe

heterogeneousarray$mixedBag:

$mixedBag=array("cat",42,8.5,false);



var_dump($mixedBag);



Thefunctionvar_dump()displaysthetypesandvaluesofeach

element(withsomewhitespaceaddedforclarity):

array(4)

{

[0]=>string(3)"cat"

[1]=>int(42)

[2]=>float(8.5)

[3]=>bool(false)



}



3.1.1.5Multidimensionalarrays

Oftendatacan'tberepresentedinasimplearrayofscalar

valuesintegers,strings,Booleans,andfloats.Somedatacan

onlyberepresentedwhenarraysholdotherarraysofvalues.

Considerrepresentingtheresultsfromthetwelvetimestable

weshowedinthepreviouschapter.Wecouldcreateanarrayfor

eachtablefromonetotwelve:

$one=array(1,2,3,4,5,6,7,8,9,10,11,12);

$two=array(2,4,6,8,10,12,14,16,18,20,22,24);

$three=array(3,6,9,12,15,18,21,24,27,30,33,36);

//etc..



orwecancreateamultidimensionalarraylikethis:

$table=array(

1=>array(1=>1,2,3,4,5,6,7,8,9,10,11,12),



2=>array(1=>2,4,6,8,10,12,14,16,18,20,22,24)



3=>array(1=>3,6,9,12,15,18,21,24,27,30,33,36

...

);



Thevariable$tableisatwo-dimensionalarray:each

elementaccessedbytheinteger1,2,3,andsoonisanarray

thatholdstheresultsofamultiplication.Valuescanbe

accessedusing[]operatorsforeachdimension.Wehave

explicitlysettheindexforthefirstelementineachrow,andfor

eachrow,allowedthetermsusedinamultiplicationtobeused

askeys.Forexample,thefollowingprintstheresultof3times

8:

//Prints24

print$table[3][8];



Example3-1showshowmorecomplexmultidimensionalarrays

canbeconstructed.



Example3-1.Examplesofmultidimensional

arraysinPHP




"http://www.w3.org/TR/html401/loose.dtd">








Multi-dimensionalarrays



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 3. Arrays, Strings, and Advanced Data Manipulation in PHP

Tải bản đầy đủ ngay(0 tr)

×