Chapter 1 Fast track to PHP Programmingin PHP begin with a $ sign (pretty much the only language I...

Post on 15-Mar-2020

2 views 0 download

Transcript of Chapter 1 Fast track to PHP Programmingin PHP begin with a $ sign (pretty much the only language I...

Chapter1FasttracktoPHPProgramming

Whatisprogramming?Haveyoueverbeengivenalistofthingstodoorlookedatinstructions?Wellthatiswhatprogrammingis,onlythelistofthingstodoorinstructionsarewritteninawaythatacomputercanunderstandthem.WewillbeexploringthePHP[https://en.wikipedia.org/wiki/PHP]programminglanguage.ForusthemainpointtorememberiswhatPHPdoesforus.InanutshellPHPcreatesHTMLcode.Whatisafasttrack?Itmeanswewillcoveronlywhatweneedjustbeforeweneedit.Thegoalistogainageneralunderstandingnotacompleteunderstanding.Thecompleteunderstandingcomeswithtime.

Computersonlydofourthings:

1. Input–Acceptinputintothecomputerviakeyboard,mouse,touchscreen,voicecommands.

2. Process–AprogramwillprocesstheInputithasbeengiveninsomefashionfromsimpleadditiontodeterminingyourcurrentlocationbasedonthegpscoordinatesitreceives.

3. Output–Thecomputerprovidesuswithoutput,generallytoourcomputerscreen,printedonpaperorspeakerstonameafew.

4. Storage–Thecomputerallowsustosaveinformation,documents,picturesevenyourcontactlistareallexamplesofstorage.

Evenmoreamazingiscomputersdoallthesethingsbyunderstandingifanelectricalswitchisturnedonoroff!Fromabasicsenseitistheseriesofswitchesthatmakeupwhatiscalledabyteanditisthepatternofhowtheyareturnedonandoffdictateswhattheymean.ForexampleZeroisusedtorepresentoffandOneisusedtorepresenton.Sothis:

01000001[https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwiDuJ-R_4bUAhVi_4MKHWWEDY0QFggoMAA&url=https%3A%2F%2Fwww.jpl.nasa.gov%2Fedu%2Fpdfs%2Fphases_chart.pdf&usg=AFQjCNGoOlgxYfkqpkDiRox9ETB8AzrMQw&sig2=a3JDZ1s_An9ufSjZSRUAAw]

representsthecapitalletterAwhenusingASCIItext[https://en.wikipedia.org/wiki/Wikipedia:ASCII].Thecomputerlooksupinatablewhatthatrepresentsthendisplaythecharacteritistoldto.Prettyamazinghowmanyelectricswitchesareturnedonandoffinjustasimpletextmessage!

Soeverythingacomputerdoesisbecausesomeonehaswrittenaseriesofinstructionstotellthecomputerwhattodo.PHPisconsideredahighlevellanguagewherewedon’thavetoworryabouttheonesandzerosbutinsteadwelearnthesyntaxandstructureoftheprogramminglanguage.

WeputPHPinstructionsinsidethePHPelementandtheendresultwillbeHTML.Forexample(meaningauselessexampleotherthantodemonstratethepoint)wecouldhavePHPsayhello(oldfashionedfirstprogramwouldbeHelloWorld)orinthecaseoftheexamplebelow"What'sup?".

Thisishowitwilllookinthebrowser:

<?phpThePHPTag

OpeningTag

?>ClosingTag

Likeallthehtmlelementsthephpelementhasanopeningandclosingtag

andmoreimportantlyifwelookatthebrowserssourcecodethisiswhatwesee.

Soitmaybeareallysimpleexampleandnotverypracticalbutthereisalotgoingon.Let'sstartwiththePHPwordprintwhichisbuiltintoPHPandjustcauseswhatevercomesafterittobecomepartoftheHTMLcode.OkIneedtotakeastepbackanddescribewhathappenswhenyourequestaPHPpageintheURL.

Let'sfollowthesteps:

1. Youtypeaurlintoyourbrowserwindow,intheaboveexamplehttp://bob.com/home.php.Thebrowserthengoestotheserverthathoststhatwebsite.

2. Theserverthenlooksforthefilehome.php(justlikeyoulookforfilesonyourcomputer).Whenitfindsthefileitnoticesithasa.phpextensionandsayswoohooaPHPfile(okmaybeitdoesnotactuallysaythat).TheserverthenreadstheentirecontentsofthefileexecutingeachlineofPHPcodeoneatatime.

3. ThePHPinterpretercreatesafile(stillcalledhome.php)thathasnothingbutHTMLcodeinitthatlooksjustlikethebrowserssourcecodeabove.SoitexecuteseachPHPinstructionthatyouhavegivenit.

4. Theservertakestheoutputfilehome.phpthathasnothingbutHTMLinitandsendsitbacktothe"clients"computer(yourcomputer)sothatyourwebbrowsercandisplayit.

Okprettyneatbutlet'sfaceit,ifthatisallPHPcandowemightaswelljustwritetheHTMLdirectlyandsaveourselvesthetrouble.Iamhopingthoughthatlittleexamplemakessenseandofcoursewearegoingtohavemoredetailedinstructionsbutwehavetolearntocrawlbeforewecanrun.

Allprogramsneedvaluesorinputthatwehavetopassintotheprograminsomefashion.Let'sjuststartwithvariables.LetusstartwithmathandthePythagoreantheorem[http://www.basic-mathematics.com/pythagorean-theorem.html]whichstates:

c2=a2+b2

noticeIwroteitbackwardssincethatishowweassignavalueinprogrammingversusthemathclasswayofa2+b2=c2.Scaredyet?Don'tworry.InBuildingTradesIlearnedthisasthe3,4,5triangletoseeifthebuilding'scornerissquare.

[https://www.google.com/maps/search/ocean+county+vocational+school/@39.9836687,-74.1876238,771a,35y,270h,39.28t/data=!3m1!1e3]TechnicallyIhelpedbuildthewallfromthecornertothedoorbutwehadtobesquareorthedoorwouldnotwork(gladtoseeitsstillstandingfrom1979)

ThewayIlearneditwasthatifyoumeasure4feetononeside(a)andputapencilmarkthere.Nextmeasure3feetontheotherside(b)andputapencilmarkthere.Nowmeasurethedistancebetweenthetwopencilpointsaslongasyourbuildingissquareitwillmeasure5feet.Oksolet'sprogram3and4intotheformulainPHPtoseeifctrulyisfiveasmyshopteachertaughtme.

andweuploadourfiletotheserverandthisiswhatshowsupinthebrowser!

OkIhaveneverusedthesquarerootmethod[http://php.net/manual/en/function.sqrt.php]builtintoPHPsoIhadtogoogleit.Clearasmud?Welllet'strytoclearthingsupabit.ThePHPline:

$a=4;iscalledanassignmentstatementtobeofficial.Theletteraiscalledavariable.AllvariablesinPHPbeginwitha$sign(prettymuchtheonlylanguageIknowofthatusessuchaconvention).Whathappenswhenwhenaprogramminglanguagecreatesavariableisthatitmakesaboxinthecomputersmemoryandgivesthatboxthenameyoutolditto.

OncePHPhastheboxitwilltakewhateveristotherightoftheequalsignandputthatvalueinthebox,beitanumber,word,imagewhatever.Inourexamplethenumber4

Thecomputerwilldothiswiththevariablebaswell.Itdoesthesamethingforthevariableconlyitwillcalculatethevaluefirstfollowingthestandardrulesformath(PEMDAS)[http://www.coolmath.com/prealgebra/05-order-of-operations/05-order-of-operations-parenthesis-PEMDAS-01]

NowletusexplorethatPHPmethodcalledprintwhichwillprinttothefilewhatevercomesafterit.Ihavealotofthingstoexplain.Ihaveusedsinglequotes.YoucanusedoublequoteshowevertobeconsistentItrytousesinglequotesforPHPanddoublequotesforHTML.NoticeinmyfirstexampleIprinted

print'<p>What\'sup?</p>';Oktheoutsidesinglequotesmakesenseastheprintmethodwillprintwhateverisinsidethequotes.SinceIwantedtoprintasinglequoteinsideofsinglequotesIhadto'escape'thequotewitha\backslashwhichmeansignorethequoteandjustprintit.JusttomakelifeconfusingIcouldhaveuseddoublequotesontheoutsideanditwouldproducethesameHTMLoutput.

print"<p>What'sup?</p>";Idon'tneedtoescapethesinglequoteinthiscase.Eitherwayworksjustrememberthatwhateveryoustartandendwithcannotbeontheinside.ToreallymesswithyourbrainIcoulddothis:

print'<p>What'."'".'sup?</p>';Theinnerblockwithfivequotesisreallyadoublequote,singequote,doublequotebutitfollowstherulesIdescribedabove.Programmingcanbefunkyattimesespeciallywhenitcomestoquotes.

Whatisupwiththeperiodsbytheway?InPHPtheperiodsareusedtoaddtexttogetherwhichwecallconcatenation.Letslookatanexample.

Line13willconcatenate4and3togetherastextsoitwilldisplayas43.Line14willadd4and3asnumberssoitwilldisplay7.

Let'slookatthesourcecodesowecanseewhatPHPcreated.

NoticethatallthePHPcreatedHTMLisonline9eventhoughinthecodetheyareonseparatelines.ThereasonisthatwenevertoldPHPtoputalinebreakin.ComputersonlydowhattheyaretoldandwenevertoldPHPtostartanewline.Youdon'tneedtoasnewlinesareforhumansbutifyouwantedtowecandothatbyprintinga\n.Ofcoursethismakestheuseofquotesevenmoreconfusing.HereIusedsingleanddoublequotes.

Let'slookattheresults.

Theendoflinemarkneedstobeprintedindoublequotesoritdoesnotworkasintended.Noticetheclosingbodyelementhasmovedtothenextlinebutthe\njustprintedonourpage.Thereisnotmuchpointinwonderingwhyit(printed\nwheninsinglequotes)islikethisbutitiswhatitis.Itisagoodexampleofwhenwemaynotunderstandwhyitislikethatbutweunderstandwhatitdoesandwecanacceptthat.

YoucanuseabuiltinPHPconstantcalledPHP_EOLwhichwillnotrequirequotesandwhichisjustthebestthingtodo.

Ionlymentionedallthisasawayofexplanationandintroduction.TheonlytimeIhavePHPputintheendoflinebreakiswhenIamhavingtroublewithmycodeandIcannotfigureitout.ItmakesiteasiertoseewhattheHTMLcodelookslikethatPHPcreated.

SowehavevariablesinPHPwhichcanbenumbersbuttheycanalsobestrings(text,words,lettersetc.).ForexampleIhavemyheadingtextinavariable.

Thiswillprintthetextinsidetheheadingone.AsareminderthisisasimpleexampleandnotverypracticalbutIamusingittodemonstrateapoint.Howeverhavingsaidthatifyouuseaframeworktocreateyourwebsitethisisprettymuchwhattheydo.

Allrightwehavesomebasicsdown:

1. PHPcreatesHTML.2. Variablesholdvaluesinthecomputer'smemory.3. Variablenamesallbeginwitha$sign.

4. Variablenamescannotcontainblankspacesorspecialcharactersotherthantheunderscore(okthisoneisnew)andshouldbeselfdocumentingmeaningIshouldnothavetoaskwhatthevariableisfor.

5. Variablescancontainnumbers,textandabunchofotherthings.6. Textiscalledastring.7. Quotesarefunky,generallyinPHPwetrytousesinglequotesaroundallstring

variables.8. Youcanhavesinglequotesontheoutsidewithdoublequotesontheinside.9. Youcanhavedoublequotesontheoutsidewithsinglequotesontheinside.10. Ifyouneedtobreaktheabovequoterulesyouwillhavetoescapethequotesonthe

insidewitha\character.11. Aperiodisusedtoconcatenatetexttogether.12. Aplussignwilladdtwonumbers(wecanguessabout-,*,/).13. ToaddlinebreaksinoursourcecodeweneedtoprintPHP_EOL.

Let'sjumpahead.Therearethreemainprogrammingstructuresinallprogramminglanguages:

Sequence–eachlineofcodeisexecutedoneaftertheotherinorder.

Selection–allowsustochoosewhichlinesofcodegetexecutedmeaningwecanskiplines.

Repetition–allowsustokeepdoingthesamelinesofcodeoverandoveragainasmanytimesasweneedto.

Let'sstartSequence,prettymuchallcodeisdoneintheorderthatitappears.Computerdon’tjumparoundintheirlistoftaskstheyneedtodo.SothesethreelinesofPHPcodejustprintsoutthethreelinesofHTMLinthesameorder.SincewehavenotprintedaEOL(endofline)marktheywillbeallinonelinebutthebrowserwilldisplaythemseparately(giveitatry).

print'<h1>Thisisaheading</h1>';

print'<p>Thisisaparagraph.</p>';

echo'<p>Youcanprintorechothetextyouwanttodisplay</p>';Thiswillshowupononeline(okinthisdocumentitwordwrapsbutwhenyouviewthepagesourceitwillnotwordwrap)likethisinthebrowserssourcecode:

<h1>Thisisaheading</h1><p>Thisisaparagraph.</p><p>Youcanprintorechothetextyouwanttodisplay</p>IwanttotalkabouttheRepetitionprogrammingstructurewhichwillrepeatlinesofcodetillyoutellittostop.LetmeshowyouthePHPsyntaxforaforloop:

for(variable;condition;increment){

//Dotheseinstructions

}NoticethedoubleslashesarePHPversiontohavecomments.Youcanhaveasmanyinstructionsasyouneed.Letmeaddsamplecodethatwillprintthatline100times:

for($i=0;$i<100;$i++){

print'<p>Iwillnottalkinclass.</p>';

}Let'slookataflowchart,whichIthinkyoucanfollowalongwith.TheSquareboxesrepresentalineofcodethatisdoingsomething.ThediamondshaperepresentsaBoolean(Booleanisfancyforayesornoquestion)questionyouhavetoanswer.Thelinesshowyouwhichwaytogonext.

Westartbyinitializingourvariable$itozero.Thismeanswewillstartwiththenumberzeroandgofromthere.Normallyaonelettervariablenameisbadbut$iisacommononeoftenusedinloopsforindex.Othercommonloopvariablesarecalledj,k,andc(jbecauseitcomesafteri,cforcountandkforkount).Sowhenweinitializeavariablethecomputercreatesaboxinitsmemoryandputsthevalueinit.

Nowweanswerthequestion.Isilessthan100?Sincetheanswerisyeswegointotheloopanddothestatementsfoundthere.Inthiscasewehavejustone:

Iwillnottalkinclass.

Wenowgotothenextboxwhichsaystoincrementthevalue.Wehave$i++whichisashortcutfor$i=$i+1.

Nowweanswerthequestionagain.Isilessthan100?Sincetheanswerisyeswegointotheloopanddothestatementsagain.Wekeepdoingthisuntilibecomes100.Sowheniis99wedothestatementsthenweincrementiby1to100

Nowweanswerthequestionagain.Isilessthan100?Sincetheanswerisnowedon’tgointotheloopandwemoveontothenextstatementaftertheloop.

Canyouseewhatthisloopwoulddo?

for($i=1;$i<=6;$i++;){

print'<h'.$i.'>Iwillnottalkinclass.</h'.$i.'>';

}Itwillprintoutall6headinglevels.Giveitatry.Istartedwithadifferentstartingpoint,oneinsteadofzero.Myconditionhadlessthanorequaltoinsteadofjustlessthan.OfcourseIwasalsoprintingoutthevalueofieachtimetocreatethedifferentHTMLelements.

Oksomaybetheforloopexamplesarenotsomethingyouwouldusebuttheyaregoodexamplesofthepotentialuses.Inthisclassweactuallydon’tusetheforloopallthatmuchbutweusetheconceptallthetime.Letmeleadyouthroughanotherexample.

Wehavetalkedaboutvariablesandwehavelearnedthat,wecanassignavaluetoavariable,wecanprintavariable,wecanusethevariableinaformulaandwecanchangethevalueofavariable.Thereisavariablethatcanhavemorethanonevalue,itiscalledanarray.Youcanthinkofanarrayasatable.Forexamplehereisatableoranarrayofmystudents:

TocreatethisinPHPcodewewouldinitializethevariabletobeanarraywiththevaluesinitlikethis:

$students=array('Adam',Bonnie,'Carol','David');Therealquestionishowdoweaccessorprintthesevariables?Atemporarywaytoprintyourarrayjusttoseeifitworksistouseprint_rmethodmadespecificallyforarrays.

print'<p>Students</p><pre>';

print_r($students);

print'</pre>';

Thiswouldprintitoutlikethis:

Thisisofcoursenotthewaytoprintyourarrayonawebpagebutitisahandywaysothatyoucan"see"whatisinthecomputersmemory.Youmaybeabletoguessthatwecanaccesseachvaluebyitsindexnumber.Ofcoursetheystartwithzerosincecomputersliketostartwith0.Wecanprintoutonevaluebyputtingtheindexnumberinthesquarebrackets:

print '<p>' . $students[0] . '</p>';

Youcouldputthisintoaforloopandprintthemalloutbyreplacingthe0withan$ivariable

for ($i=0;$i<count($students);$i++){

print '<p>' . $students[$i] . '</p>';

}

HoweversinceitissocommontousearraysinPHPwehaveaspecialloopstructurejustforthem.Itiscalledaforeachloopandthisiswhatweshoulduseforarrays.

Thesyntaxfortheforeachloopis:

foreach(array-variable-nameasone-row-of-the-array){

//Dotheseinstructions

}

Trytonameyourarraysinthepluralform,iestudents,cars,people.Thenusethesingularnamefortheasvariable,iestudent,car,personasitmakesforeasierunderstandingofthecode.

Let'slookattheforeachflowcharttoseeifyoucanfollowthrough:

Inthiscasewehaveanarrayvariableandthequestiontoaskis:Istherearowofdata?Ifyeswedothestatements.Theincrementisautomaticastheforeachloopwillautomaticallygotothenextrecordtilltherearenomore.Let'slookatsomesamplecode:

<?php

$students=array('Adam','Bonnie','Carol', 'David');

print '<h1>Class List</h1>';

print '<ol>';

foreach ($students as $student){

print '<li>' . $student . '</li>';

}

print '</ol>'; ?>

Acoupleofthingstonotice.SinceIamprintinganorderedlistIneedtoprinttheopenandclosingolelementsoutsideoftheloop.TheHTMLcodethatwillberepeatedisthelistitem(li)insidetheloop.Seehowthevariable$studentisfortheonestudentatatime.Theoutputfromthiscodelookslikethis:

WiththecorrespondingHTMLsourcecodecreatedlookinglikethis(wedidnotputinanyEOF)

Clearasmud?IamtryingtotakequantumleapswithyourunderstandingandIamhopingyouareabletofollowalongwiththebasicsthatIamgivingyou.Aonecolumnarrayisfairlystraightforwardbutgenerallywealwayshavemorethanonecolumn.Iwanttoshowyouatwocolumnarray(morethantwoisreallyjustthesamesyntaxjustmoreofit).Tomakeatwocolumnarrayyoujusthaveeacharraybox(likewereAdamwasinthebox)beanarrayitself.Youcanthinkofanarraywithmorethanonecolumnasanarrayinanarray.HereisthecodetocreateatwocolumnarrayofthefreezeoverdatesforLake

Champlain.Ihavetriedtohelpyoupictureitasanarraywithmanyarraysinsideit.Itmaytakeawhiletomakesense.

$freezeDates = array( array(2000, 'not closed'), array(2001, '2001-03-02'), array(2002, 'not closed'), array(2003, '2003-02-15'), array(2004, '2004-01-27'), array(2005, '2003-03-08'), array(2006, 'not closed'), array(2007, '2007-03-02'), array(2008, 'not closed'), array(2009, 'not closed'), array(2010, 'not closed'), array(2011, 'not closed'), array(2012, 'not closed'), array(2013, 'not closed'), array(2014, '2014-02-12'), array(2015, '2015-02-16')

);

Noticehoweachrow(exceptforthelastone)hasacommaattheend.Asareminder,tocreateaone-dimensionalarray(onecolumnarray)itwouldbe:

$students=array('Adam','Bonnie','Carol','David');

So'Adam'wasoneelementinthearrayjustlikearray(2000,'notclosed')isoneelementinthearray.Wearejustmakingtheoneelementbigger.Itisalittlebitmorecomplicatedwhenloopingthroughthemulticolumnarrayasyouneedtospecifywhichcolumntodisplay.Remembertostartwithzero.

foreach ($freezeDates as $freezeDate) {

print '<p>' . $freezeDate[0] . ' – ' . $freezeDate[1] . '</p>';

}

Makesense?Arraysareusedheavilyintheweb.Howwepopulatethearraychangesasyougainmoreexperiencebutloopingthroughthearrayisthesame.Itwillbehardatfirstbutonceyouwrapyourheadarounditwon'tbeasbadasitsoundsthefirsttime.Thisvideomayhelp(especiallywhenyoumakeamistake)

CodeWalkThrough:https://www.youtube.com/watch?v=9WEIGziEylo&list=PLxWIQk1hqg09WQMlrnyjK8sVsrdoqo8lJ&index=14&t=545s

SelfTestQuestions

1. ThePHPcommandprintcauseswhateverthatcomesafterittobecome__________?2. Thiswillprint:

a. print1+2*3; b. print10/2-3; c. print8+20*2-6; d. print(8+2)*(6-2)+2;

Forthenextfewquestionsusethesevalues:$a=1;$b=2;$c=3;

e. print$a.$b f. print($a+$b)*$c g. print$a+$b*$c

3. T(true)orF(false)a. print'WelcometotheJungle'; b. print"<h2>WelcometotheJungle</h2>"; c. echo'<p>WelcometotheJungle</p>'; d. print'Let'sGoFishing!'; e. print'Let\'sGoFishing!'; f. echo"Let'sGoFishing!";

4. WriteaPHPstatementtoprintyourname. 5. WriteaPHPstatementtoprintaheadingoneelementwiththetextDon'tMakeMe

Think6. Giventhisarray$numbers=array(3,33,37,51,57,21);

whatwillthisstatementprint?print'<p>Number:'.$numbers[3];

7. Createanarrayforyourtopthreefavoriteplaces,printthearray.

ChallengeQuestions

1. Personal Information Write some php code that stores the following information in respective variables and then prints it on the page.

- Your name - Your address, with city, state and ZIP - Your telephone number - Your college major

2. Sales Prediction

A company has determined that its annual profit is typically 23 percent of total sales. Write some php code that will display the profit made from an amount that is stored as a variable. Print the profit on screen.

3. Distance Traveled Assuming there are no accidents or delays, the distance that a car travels down the interstate can be calculated with the following formula: Distance = Speed X Time A car is traveling at 70 miles per hour. Write some php code that displays the following:

- The distance the car will travel in 6 hours - The distance the car will travel in 10 hours - The distance the car will travel in 15 hours

4. Day of the Week Write some php code that uses an array to print the day of the week based on a number, where 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday, 7 = Sunday.

5. Roman Numerals Write some php code that prints a roman numeral from 1 to 10 depending on the value of another variable. (Hint: store the roman numerals in an array)

AnswerstoChallengeQuestions

1. Answer: <?php $name = “Alec”; $address = “388 College St, Burlington Vt, 05405”; $number = “123-456-7890”; $major = “Computer Science”; print $name; print $address; print $number; print $major; ?> 2. Answer:

<?php $totalSales = 100; print 0.23 * $totalSales; ?>

3. Answer: <?php $speed = 70; print $speed * 6; print $speed * 10; print $speed * 15; ?> 4. Answer:

<?php $array = [Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday]; $day = 1; $print $array[$day]; ?>

5.Answer:

<?php $number = 5; $romanNumerals = [‘I’, ‘II’, ‘III’, ‘IV’, ‘V’, ‘VI’, ‘VII’, ‘VIII’, ‘IX’, ‘X’]; print $romanNumerals[$number - 1]; ?>