SlideShare a Scribd company logo
Introduction to php 
Synapse india Reviews on PHP 
Website Development
What we'll cover 
• A short history of php 
• Parsing 
• Variables 
• Arrays 
• Operators 
• Functions 
• Control Structures 
• External Data Files
Background 
• PHP is server side scripting system 
• PHP stands for "PHP: Hypertext Preprocessor" 
• Syntax based on Perl, Java, and C 
• Very good for creating dynamic content 
• Powerful, but somewhat risky! 
• If you want to focus on one system for dynamic 
content, this is a good one to choose
History 
• Started as a Perl hack in 1994 by Rasmus Lerdorf 
(to handle his resume), developed to PHP/FI 2.0 
• By 1997 up to PHP 3.0 with a new parser engine 
by Zeev Suraski and Andi Gutmans 
• Version 5.2.4 is current version, rewritten by Zend 
(www.zend.com) to include a number of features, 
such as an object model 
• Current is version 5 
• php is one of the premier examples of what an 
open source project can be
About Zend 
• A Commercial Enterprise 
• Zend provides Zend engine for PHP for free 
• They provide other products and services for a fee 
• Server side caching and other optimizations 
• Encoding in Zend's intermediate format to protect 
source code 
• IDE-a developer's package with tools to make life 
easier 
• Support and training services 
• Zend's web site is a great resource
PHP 5 Architecture 
• Zend engine as parser (Andi Gutmans and Zeev Suraski) 
• SAPI is a web server abstraction layer 
• PHP components now self contained (ODBC, Java, 
LDAP, etc.) 
• This structure is a good general design for software 
(compare to OSI model, and middleware applications)
PHP Scripts 
• Typically file ends in .php--this is set by the web 
server configuration 
• Separated in files with the <?php ?> tag 
• php commands can make up an entire file, or can 
be contained in html--this is a choice…. 
• Program lines end in ";" or you get an error 
• Server recognizes embedded script and executes 
• Result is passed to browser, source isn't visible 
<P> 
<?php $myvar = "Hello World!"; 
echo $myvar; 
?> 
</P>
Parsing 
• We've talk about how the browser can read a text 
file and process it, that's a basic parsing method 
• Parsing involves acting on relevant portions of a 
file and ignoring others 
• Browsers parse web pages as they load 
• Web servers with server side technologies like php 
parse web pages as they are being passed out to 
the browser 
• Parsing does represent work, so there is a cost
Two Ways 
• You can embed sections of php inside html: 
<BODY> 
<P> 
<?php $myvar = "Hello World!"; 
echo $myvar; 
</BODY> 
• Or you can call html from php: 
<?php 
echo "<html><head><title>Howdy</title> 
…? 
>
What do we know already? 
• Much of what we learned about javascript 
holds true in php (but not all!), and other 
languages as well 
$name = "bil"; 
echo "Howdy, my name is $name"; 
echo "What will $name be in this line?"; 
echo 'What will $name be in this line?'; 
echo 'What's wrong with this line?'; 
if ($name == "bil") 
{ 
// Hey, what's this? 
echo "got a match!"; 
}
Variables 
• Typed by context (but one can force type), so it's 
loose 
• Begin with "$" (unlike javascript!) 
• Assigned by value 
• $foo = "Bob"; $bar = $foo; 
• Assigned by reference, this links vars 
• $bar = &$foo; 
• Some are preassigned, server and env vars 
• For example, there are PHP vars, eg. PHP_SELF, 
HTTP_GET_VARS 00
phpinfo() 
• The phpinfo() function shows the php 
environment 
• Use this to read system and server variables, 
setting stored in php.ini, versions, and 
modules 
• Notice that many of these data are in arrays 
• This is the first script you should write… 
0000__pphhppiinnffoo..pphhpp
Variable Variables 
• Using the value of a variable as the name of 
a second variable) 
$a = "hello"; 
$$a = "world"; 
• Thus: 
echo "$a ${$a}"; 
• Is the same as: 
echo "$a $hello"; 
• But $$a echoes as "$hello"….
Operators 
• AArriitthhmmeettiicc ((++,, --,, **,, //,, %%)) aanndd SSttrriinngg ((..)) 
• AAssssiiggnnmmeenntt ((==)) aanndd ccoommbbiinneedd aassssiiggnnmmeenntt 
$a = 3; 
$a += 5; // sets $a to 8; 
$b = "Hello "; 
$b .= "There!"; // sets $b to "Hello There!"; 
• BBiittwwiissee ((&&,, ||,, ^^,, ~~,, <<<<,, >>>>)) 
• $a ^ $b(Xor: Bits that are set in $a or $b but not 
both are set.) 
• ~ $a (Not: Bits that are set in $a are not set, 
and vice versa.) 
• CCoommppaarriissoonn ((====,, ======,, !!==,, !!====,, <<,, >>,, <<==,, >>==))
Coercion 
• Just like javascript, php is loosely typed 
• Coercion occurs the same way 
• If you concatenate a number and string, the 
number becomesa string 
1177__ccooeerrcciioonn..pphhpp
Operators: The Movie 
• EErrrroorr CCoonnttrrooll ((@@)) 
• WWhheenn tthhiiss pprreecceeddeess aa ccoommmmaanndd,, eerrrroorrss ggeenneerraatteedd aarree iiggnnoorreedd 
((aalllloowwss ccuussttoomm mmeessssaaggeess)) 
• EExxeeccuuttiioonn ((`` iiss ssiimmiillaarr ttoo tthhee sshheellll__eexxeecc(()) 
ffuunnccttiioonn)) 
• YYoouu ccaann ppaassss aa ssttrriinngg ttoo tthhee sshheellll ffoorr eexxeeccuuttiioonn:: 
$$oouuttppuutt == ``llss --aall``;; 
$$oouuttppuutt == sshheellll__eexxeecc((""llss --aall""));; 
• TThhiiss iiss oonnee rreeaassoonn ttoo bbee ccaarreeffuull aabboouutt uusseerr sseett vvaarriiaabblleess!! 
• IInnccrreemmeennttiinngg//DDeeccrreemmeennttiinngg 
++++$$aa ((IInnccrreemmeennttss bbyy oonnee,, tthheenn rreettuurrnnss $$aa..)) 
$$aa++++ ((RReettuurrnnss $$aa,, tthheenn iinnccrreemmeennttss $$aa bbyy oonnee..)) 
----$$aa ((DDeeccrreemmeennttss $$aa bbyy oonnee,, tthheenn rreettuurrnnss $$aa..)) 
$$aa---- ((RReettuurrnnss $$aa,, tthheenn ddeeccrreemmeennttss $$aa bbyy oonnee..))
Son of the Valley of Operators 
• Logical 
$a and $b And True if both $a and $b are true. 
$a or $b Or True if either $a or $b is true. 
$a xor $b Xor True if either $a or $b is true, 
but not both. 
! $a Not True if $a is not true. 
$a && $b And True if both $a and $b are true. 
$a || $b Or True if either $a or $b is true. 
• The two ands and ors have different 
precedence rules, "and" and "or" are lower 
precedence than "&&" and "||" 
• Use parentheses to resolve precedence 
problems or just to be clearer
Control Structures 
• Wide Variety available 
• if, else, elseif 
• while, do-while 
• for, foreach 
• break, continue, switch 
• require, include, require_once, include_once
Control Structures 
• Mostly parallel to what we've covered 
already in javascript 
• if, elseif, else, while, for, foreach, break and 
continue
Switch 
• Switch, which we've seen, is very useful 
• These two do the same 
things…. 
if ($i == 0) { 
echo "i equals 0"; 
} elseif ($i == 1) { 
echo "i equals 1"; 
} elseif ($i == 2) { 
echo "i equals 2"; 
} 
switch ($i) { 
case 0: 
echo "i equals 0"; 
break; 
case 1: 
echo "i equals 1"; 
break; 
case 2: 
echo "i equals 2"; 
break; 
}
Nesting Files 
• i require(), include(), inncclluuddee__oonnccee(()),, rreeqquuiirree__oonnccee(()) aarree 
uusseedd ttoo bbrriinngg iinn aann eexxtteerrnnaall ffiillee 
• TThhiiss lleettss yyoouu uussee tthhee ssaammee cchhuunnkk ooff ccooddee iinn aa nnuummbbeerr 
ooff ppaaggeess,, oorr rreeaadd ootthheerr kkiinnddss ooff ffiilleess iinnttoo yyoouurr pprrooggrraamm 
• BBee VVEERRYY ccaarreeffuull ooff uussiinngg tthheessee aannyywwhheerree cclloossee ttoo uusseerr 
iinnppuutt----iiff aa hhaacckkeerr ccaann ssppeecciiffyy tthhee ffiillee ttoo bbee iinncclluuddeedd,, 
tthhaatt ffiillee wwiillll eexxeeccuuttee wwiitthhiinn yyoouurr ssccrriipptt,, wwiitthh wwhhaatteevveerr 
rriigghhttss yyoouurr ssccrriipptt hhaass ((rreeaaddffiillee iiss aa ggoooodd aalltteerrnnaattiivvee iiff 
yyoouu jjuusstt wwaanntt tthhee ffiillee,, bbuutt ddoonn'tt nneeeedd ttoo eexxeeccuuttee iitt)) 
• YYeess,, VViirrggiinniiaa,, rreemmoottee ffiilleess ccaann bbee ssppeecciiffiieedd
Example: A Dynamic Table 
• I hate writing html tables 
• You can build one in php 
• This example uses pictures and builds a 
table with pictures in one column, and 
captions in another 
• The captions are drawn from text files 
• I'm using tables, but you could use css for 
placement easily…
Arrays 
• You can create an array with the array function, or use the 
explode function (this is very useful when reading files into 
web programs…) 
$my_array = array(1, 2, 3, 4, 5); 
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; 
$pieces = explode(" ", $pizza); 
• An array is simply a variable representing a keyed list 
• A list of values or variables 
• If a variable, that var can also be an array 
• Each variable in the list has a key 
• The key can be a number or a text label
Arrays 
• Arrays are lists, or lists of lists, or list of lists of 
lists, you get the idea--Arrays can be multi-dimensional 
• Array elements can be addressed by either by 
number or by name (strings) 
• If you want to see the structure of an array, use the 
print_r function to recursively print an array inside 
of pre tags
Text versus Keys 
• Text keys work like number keys (well, 
really, it's the other way around--number 
keys are just labels) 
• You assign and call them the same way, 
except you have to assign the label to the 
value or variables, eg: 
echo "$my_text_array[third]"; 
$my_text_array = array(first=>1, second=>2, third=>3); 
echo "<pre>"; 
print_r($my_text_array); 
echo "</pre>";
Walking Arrays 
• Use a loop, eg a foreach loop to walk 
through an array 
• while loops also work for arrays with 
numeric keys--just set a variable for the 
loop, and make sure to increment that 
variable within the loop 
$colors = array('red', 'blue', 'green', 'yellow'); 
foreach ($colors as $color) { 
echo "Do you like $color?n"; 
} 
0055__aarrrraayyss..pphhpp
05_arrays.php 
• You can't echo an 
array directly… 
• You can walk through 
an echo or print() line 
by line 
• You can use print_r(), 
this will show you the 
structure of complex 
arrays--that output is 
to the right, and it's 
handy for learning the 
structure of an array 
Array 
( 
[1] => Array 
( 
[sku] => A13412 
[quantity] => 10 
[item] => Whirly Widgets 
[price] => .50 
) 
[2] => Array 
( 
[sku] => A43214 
[quantity] => 142 
[item] => Widget Nuts 
[price] => .05 
)
Multidimensional Arrays 
• A one dimensional array is a list, a spreadsheet or other columnar data 
is two dimensional… 
• Basically, you can make an array of arrays 
$multiD = array 
( 
"fruits" => array("myfavorite" => "orange", "yuck" => 
"banana", "yum" => "apple"), 
"numbers" => array(1, 2, 3, 4, 5, 6), 
"holes" => array("first", 5 => "second", "third") 
); 
• The structure can be built array by array, or declared with a single 
statement 
• You can reference individual elements by nesting: 
echo "<p>Yes, we have no " . $multiD["fruits"]["yuck"] . " 
(ok by me).</p>"; 
0011aa__aarrrraayyss..pphhpp
Getting Data into arrays 
• You can directly read data into individual 
array slots via a direct assignment: 
$pieces[5] = "poulet resistance"; 
• From a file: 
• Use the file command to read a delimited file 
(the delimiter can be any unique char): 
$pizza = file(./our_pizzas.txt) 
• Use explode to create an array from a line 
within a loop: 
$pieces = explode(" ", $pizza);
The Surface 
• The power of php lies partially in the wealth of 
functions---for example, the 40+ array functions 
• array_flip() swaps keys for values 
• array_count_values() returns an associative array of all 
values in an array, and their frequency 
• array_rand() pulls a random element 
• array_unique() removes duppies 
• array_walk() applies a user defined function to each 
element of an array (so you can dice all of a dataset) 
• count() returns the number of elements in an array 
• array_search() returns the key for the first match in an 
array 
0088__aarrrraayy__ffuu..pphhpp
Using External Data 
• You can build dynamic pages with just the 
information in a php script 
• But where php shines is in building pages 
out of external data sources, so that the web 
pages change when the data does 
• Most of the time, people think of a database 
like MySQL as the backend, but you can 
also use text or other files, LDAP, pretty 
much anything….
Standard data files 
• Normally you'd use a tab delimited file, but you can 
use pretty much anything as a delimiter 
• Files get read as arrays, one line per slot 
• Remember each line ends in n, you should clean 
this up, and be careful about white space 
• Once the file is read, you can use explode to break 
the lines into fields, one at a time, in a loop….
Standard data files 
• You can use trim() to clean white space and 
returns instead of str_replace() 
• Notice that this is building an array of arrays 
$iitteemmss==ffiillee((""..//mmyyddaattaa..ttxxtt""));; 
ffoorreeaacchh (($$iitteemmss aass $$lliinnee)) 
{{ 
$$lliinnee == ssttrr__rreeppllaaccee((""nn"",, """",, $$lliinnee));; 
$$lliinnee == eexxppllooddee((""tt"",, $$lliinnee));; 
//// ddoo ssoommeetthhiinngg wwiitthh $$lliinnee aarrrraayy 
}}
Useful string functions 
• str_replace() 
• trim(), ltrim(), rtrim() 
• implode(), explode() 
• addslashes(), stripslashes() 
• htmlentities(), html_entity_decode(), 
htmlspecialchars() 
• striptags()
06_more_arrays.php 
• This is a simple script to read and process a text 
file 
• The data file is tab delimited and has the column 
titles as the first line of the file
How it works 
• The script uses the first line to build text labels for 
the subsequent lines, so that the array elements 
can be called by the text label 
• If you add a new column, this script 
compensates 
• Text based arrays are not position dependent… 
• This script could be the basis of a nice function 
• There are two version of this, calling two different 
datafiles, but that's the only difference
06a_more_arrays.php 
• This version shows how to dynamically build a table in the 
html output
Alternative syntax 
• Applies to if, while, for, foreach, and switch 
• Change the opening brace to a colon 
• Change the closing brace to an endxxx 
statement 
<?php if ($a == 5): ?> 
A is equal to 5 
<?php endif; ?> 
<?php 
if ($a == 5): 
echo "a equals 5"; 
echo "..."; 
else: 
echo "a is not 5"; 
endif; 
?> 07

More Related Content

PPT
Synapseindia reviews sharing intro on php
PPT
PPT
rtwerewr
PPT
Php classes in mumbai
PPT
PHP - Introduction to PHP Functions
PPTX
PHP Basics and Demo HackU
PDF
Working with text, Regular expressions
KEY
FizzBuzzではじめるテスト
Synapseindia reviews sharing intro on php
rtwerewr
Php classes in mumbai
PHP - Introduction to PHP Functions
PHP Basics and Demo HackU
Working with text, Regular expressions
FizzBuzzではじめるテスト

What's hot (19)

PPTX
KEY
Rails for PHP Developers
PDF
Your code sucks, let's fix it! - php|tek13
PPT
PHP - Introduction to PHP Date and Time Functions
PDF
Introduction to Perl and BioPerl
KEY
Introduction to Perl Best Practices
PPTX
Bioinformatics p1-perl-introduction v2013
PPTX
Bioinformatica p6-bioperl
PPT
LPW: Beginners Perl
PDF
PHP 7 – What changed internally? (PHP Barcelona 2015)
PDF
Code with style
PDF
Code with Style - PyOhio
PPT
PHP Tutorial (funtion)
PPT
03 Php Array String Functions
PDF
Perl6 grammars
PPTX
Bioinformatics p5-bioperl v2013-wim_vancriekinge
PDF
Perl.Hacks.On.Vim
Rails for PHP Developers
Your code sucks, let's fix it! - php|tek13
PHP - Introduction to PHP Date and Time Functions
Introduction to Perl and BioPerl
Introduction to Perl Best Practices
Bioinformatics p1-perl-introduction v2013
Bioinformatica p6-bioperl
LPW: Beginners Perl
PHP 7 – What changed internally? (PHP Barcelona 2015)
Code with style
Code with Style - PyOhio
PHP Tutorial (funtion)
03 Php Array String Functions
Perl6 grammars
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Perl.Hacks.On.Vim
Ad

Viewers also liked (8)

PDF
Php array
PDF
PHP Unit 4 arrays
PPTX
PHP array 1
PPT
Php array
PPT
PPSX
Php array
PPT
PHP: Arrays
PDF
PHP Arrays
Php array
PHP Unit 4 arrays
PHP array 1
Php array
Php array
PHP: Arrays
PHP Arrays
Ad

Similar to Synapseindia reviews on array php (20)

PPT
PHP - Introduction to PHP
PPT
PPT
MIND sweeping introduction to PHP
PPT
PPT
Synapseindia reviews sharing intro on php
PPT
PPT
Php introduction with history of php
PPT
php fundamental
PDF
Php Introduction nikul
PDF
DIG1108C Lesson3 Fall 2014
PPTX
PHP Basics
PPT
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
PPT
Prersentation
PPTX
Lecture 9 - Intruduction to BOOTSTRAP.pptx
PPTX
PHP language presentation
PDF
Php Crash Course - Macq Electronique 2010
PPTX
Dev traning 2016 basics of PHP
PDF
UNIT4.pdf php basic programming for begginers
PHP - Introduction to PHP
MIND sweeping introduction to PHP
Synapseindia reviews sharing intro on php
Php introduction with history of php
php fundamental
Php Introduction nikul
DIG1108C Lesson3 Fall 2014
PHP Basics
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Prersentation
Lecture 9 - Intruduction to BOOTSTRAP.pptx
PHP language presentation
Php Crash Course - Macq Electronique 2010
Dev traning 2016 basics of PHP
UNIT4.pdf php basic programming for begginers

More from saritasingh19866 (20)

PPT
Synapseindia drupal intro 0
PPT
Synapseindia mobile apps cellular networks and mobile computing part1
PPT
Synapse india reviews on mobile and tablet computing
PPT
Synapse india complaints iphone or ipad application development
ODP
Synapse india reviews on cross plateform mobile apps development
PPT
Synapse india reviews on android and ios
PPT
Synapse india reviews on i phone and android os
ODP
Synapse india reviews on share point development
ODP
Synapse india reviews on security for the share point developer
ODP
Synapse india reviews on gui programming in .net
ODP
Synapse india reviews on mobile application development
PPT
Synapse india reviews on android application
ODP
Synapse india reviews on asp.net mobile application
PPT
Synapse india reviews on php website development
PPT
Synapse india reviews on php and sql
PPT
Synapseindia reviews about Basic Networking
PPT
Synapseindia revirews about networking
POT
Synapseindia reviews
PPT
Synapse india reviews abot Networking Concept
ODP
Synapse india reviews
Synapseindia drupal intro 0
Synapseindia mobile apps cellular networks and mobile computing part1
Synapse india reviews on mobile and tablet computing
Synapse india complaints iphone or ipad application development
Synapse india reviews on cross plateform mobile apps development
Synapse india reviews on android and ios
Synapse india reviews on i phone and android os
Synapse india reviews on share point development
Synapse india reviews on security for the share point developer
Synapse india reviews on gui programming in .net
Synapse india reviews on mobile application development
Synapse india reviews on android application
Synapse india reviews on asp.net mobile application
Synapse india reviews on php website development
Synapse india reviews on php and sql
Synapseindia reviews about Basic Networking
Synapseindia revirews about networking
Synapseindia reviews
Synapse india reviews abot Networking Concept
Synapse india reviews

Recently uploaded (20)

PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
master seminar digital applications in india
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Pharma ospi slides which help in ospi learning
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Basic Mud Logging Guide for educational purpose
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Cell Structure & Organelles in detailed.
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
RMMM.pdf make it easy to upload and study
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Final Presentation General Medicine 03-08-2024.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
master seminar digital applications in india
PPH.pptx obstetrics and gynecology in nursing
Pharma ospi slides which help in ospi learning
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Basic Mud Logging Guide for educational purpose

Synapseindia reviews on array php

  • 1. Introduction to php Synapse india Reviews on PHP Website Development
  • 2. What we'll cover • A short history of php • Parsing • Variables • Arrays • Operators • Functions • Control Structures • External Data Files
  • 3. Background • PHP is server side scripting system • PHP stands for "PHP: Hypertext Preprocessor" • Syntax based on Perl, Java, and C • Very good for creating dynamic content • Powerful, but somewhat risky! • If you want to focus on one system for dynamic content, this is a good one to choose
  • 4. History • Started as a Perl hack in 1994 by Rasmus Lerdorf (to handle his resume), developed to PHP/FI 2.0 • By 1997 up to PHP 3.0 with a new parser engine by Zeev Suraski and Andi Gutmans • Version 5.2.4 is current version, rewritten by Zend (www.zend.com) to include a number of features, such as an object model • Current is version 5 • php is one of the premier examples of what an open source project can be
  • 5. About Zend • A Commercial Enterprise • Zend provides Zend engine for PHP for free • They provide other products and services for a fee • Server side caching and other optimizations • Encoding in Zend's intermediate format to protect source code • IDE-a developer's package with tools to make life easier • Support and training services • Zend's web site is a great resource
  • 6. PHP 5 Architecture • Zend engine as parser (Andi Gutmans and Zeev Suraski) • SAPI is a web server abstraction layer • PHP components now self contained (ODBC, Java, LDAP, etc.) • This structure is a good general design for software (compare to OSI model, and middleware applications)
  • 7. PHP Scripts • Typically file ends in .php--this is set by the web server configuration • Separated in files with the <?php ?> tag • php commands can make up an entire file, or can be contained in html--this is a choice…. • Program lines end in ";" or you get an error • Server recognizes embedded script and executes • Result is passed to browser, source isn't visible <P> <?php $myvar = "Hello World!"; echo $myvar; ?> </P>
  • 8. Parsing • We've talk about how the browser can read a text file and process it, that's a basic parsing method • Parsing involves acting on relevant portions of a file and ignoring others • Browsers parse web pages as they load • Web servers with server side technologies like php parse web pages as they are being passed out to the browser • Parsing does represent work, so there is a cost
  • 9. Two Ways • You can embed sections of php inside html: <BODY> <P> <?php $myvar = "Hello World!"; echo $myvar; </BODY> • Or you can call html from php: <?php echo "<html><head><title>Howdy</title> …? >
  • 10. What do we know already? • Much of what we learned about javascript holds true in php (but not all!), and other languages as well $name = "bil"; echo "Howdy, my name is $name"; echo "What will $name be in this line?"; echo 'What will $name be in this line?'; echo 'What's wrong with this line?'; if ($name == "bil") { // Hey, what's this? echo "got a match!"; }
  • 11. Variables • Typed by context (but one can force type), so it's loose • Begin with "$" (unlike javascript!) • Assigned by value • $foo = "Bob"; $bar = $foo; • Assigned by reference, this links vars • $bar = &$foo; • Some are preassigned, server and env vars • For example, there are PHP vars, eg. PHP_SELF, HTTP_GET_VARS 00
  • 12. phpinfo() • The phpinfo() function shows the php environment • Use this to read system and server variables, setting stored in php.ini, versions, and modules • Notice that many of these data are in arrays • This is the first script you should write… 0000__pphhppiinnffoo..pphhpp
  • 13. Variable Variables • Using the value of a variable as the name of a second variable) $a = "hello"; $$a = "world"; • Thus: echo "$a ${$a}"; • Is the same as: echo "$a $hello"; • But $$a echoes as "$hello"….
  • 14. Operators • AArriitthhmmeettiicc ((++,, --,, **,, //,, %%)) aanndd SSttrriinngg ((..)) • AAssssiiggnnmmeenntt ((==)) aanndd ccoommbbiinneedd aassssiiggnnmmeenntt $a = 3; $a += 5; // sets $a to 8; $b = "Hello "; $b .= "There!"; // sets $b to "Hello There!"; • BBiittwwiissee ((&&,, ||,, ^^,, ~~,, <<<<,, >>>>)) • $a ^ $b(Xor: Bits that are set in $a or $b but not both are set.) • ~ $a (Not: Bits that are set in $a are not set, and vice versa.) • CCoommppaarriissoonn ((====,, ======,, !!==,, !!====,, <<,, >>,, <<==,, >>==))
  • 15. Coercion • Just like javascript, php is loosely typed • Coercion occurs the same way • If you concatenate a number and string, the number becomesa string 1177__ccooeerrcciioonn..pphhpp
  • 16. Operators: The Movie • EErrrroorr CCoonnttrrooll ((@@)) • WWhheenn tthhiiss pprreecceeddeess aa ccoommmmaanndd,, eerrrroorrss ggeenneerraatteedd aarree iiggnnoorreedd ((aalllloowwss ccuussttoomm mmeessssaaggeess)) • EExxeeccuuttiioonn ((`` iiss ssiimmiillaarr ttoo tthhee sshheellll__eexxeecc(()) ffuunnccttiioonn)) • YYoouu ccaann ppaassss aa ssttrriinngg ttoo tthhee sshheellll ffoorr eexxeeccuuttiioonn:: $$oouuttppuutt == ``llss --aall``;; $$oouuttppuutt == sshheellll__eexxeecc((""llss --aall""));; • TThhiiss iiss oonnee rreeaassoonn ttoo bbee ccaarreeffuull aabboouutt uusseerr sseett vvaarriiaabblleess!! • IInnccrreemmeennttiinngg//DDeeccrreemmeennttiinngg ++++$$aa ((IInnccrreemmeennttss bbyy oonnee,, tthheenn rreettuurrnnss $$aa..)) $$aa++++ ((RReettuurrnnss $$aa,, tthheenn iinnccrreemmeennttss $$aa bbyy oonnee..)) ----$$aa ((DDeeccrreemmeennttss $$aa bbyy oonnee,, tthheenn rreettuurrnnss $$aa..)) $$aa---- ((RReettuurrnnss $$aa,, tthheenn ddeeccrreemmeennttss $$aa bbyy oonnee..))
  • 17. Son of the Valley of Operators • Logical $a and $b And True if both $a and $b are true. $a or $b Or True if either $a or $b is true. $a xor $b Xor True if either $a or $b is true, but not both. ! $a Not True if $a is not true. $a && $b And True if both $a and $b are true. $a || $b Or True if either $a or $b is true. • The two ands and ors have different precedence rules, "and" and "or" are lower precedence than "&&" and "||" • Use parentheses to resolve precedence problems or just to be clearer
  • 18. Control Structures • Wide Variety available • if, else, elseif • while, do-while • for, foreach • break, continue, switch • require, include, require_once, include_once
  • 19. Control Structures • Mostly parallel to what we've covered already in javascript • if, elseif, else, while, for, foreach, break and continue
  • 20. Switch • Switch, which we've seen, is very useful • These two do the same things…. if ($i == 0) { echo "i equals 0"; } elseif ($i == 1) { echo "i equals 1"; } elseif ($i == 2) { echo "i equals 2"; } switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; }
  • 21. Nesting Files • i require(), include(), inncclluuddee__oonnccee(()),, rreeqquuiirree__oonnccee(()) aarree uusseedd ttoo bbrriinngg iinn aann eexxtteerrnnaall ffiillee • TThhiiss lleettss yyoouu uussee tthhee ssaammee cchhuunnkk ooff ccooddee iinn aa nnuummbbeerr ooff ppaaggeess,, oorr rreeaadd ootthheerr kkiinnddss ooff ffiilleess iinnttoo yyoouurr pprrooggrraamm • BBee VVEERRYY ccaarreeffuull ooff uussiinngg tthheessee aannyywwhheerree cclloossee ttoo uusseerr iinnppuutt----iiff aa hhaacckkeerr ccaann ssppeecciiffyy tthhee ffiillee ttoo bbee iinncclluuddeedd,, tthhaatt ffiillee wwiillll eexxeeccuuttee wwiitthhiinn yyoouurr ssccrriipptt,, wwiitthh wwhhaatteevveerr rriigghhttss yyoouurr ssccrriipptt hhaass ((rreeaaddffiillee iiss aa ggoooodd aalltteerrnnaattiivvee iiff yyoouu jjuusstt wwaanntt tthhee ffiillee,, bbuutt ddoonn'tt nneeeedd ttoo eexxeeccuuttee iitt)) • YYeess,, VViirrggiinniiaa,, rreemmoottee ffiilleess ccaann bbee ssppeecciiffiieedd
  • 22. Example: A Dynamic Table • I hate writing html tables • You can build one in php • This example uses pictures and builds a table with pictures in one column, and captions in another • The captions are drawn from text files • I'm using tables, but you could use css for placement easily…
  • 23. Arrays • You can create an array with the array function, or use the explode function (this is very useful when reading files into web programs…) $my_array = array(1, 2, 3, 4, 5); $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); • An array is simply a variable representing a keyed list • A list of values or variables • If a variable, that var can also be an array • Each variable in the list has a key • The key can be a number or a text label
  • 24. Arrays • Arrays are lists, or lists of lists, or list of lists of lists, you get the idea--Arrays can be multi-dimensional • Array elements can be addressed by either by number or by name (strings) • If you want to see the structure of an array, use the print_r function to recursively print an array inside of pre tags
  • 25. Text versus Keys • Text keys work like number keys (well, really, it's the other way around--number keys are just labels) • You assign and call them the same way, except you have to assign the label to the value or variables, eg: echo "$my_text_array[third]"; $my_text_array = array(first=>1, second=>2, third=>3); echo "<pre>"; print_r($my_text_array); echo "</pre>";
  • 26. Walking Arrays • Use a loop, eg a foreach loop to walk through an array • while loops also work for arrays with numeric keys--just set a variable for the loop, and make sure to increment that variable within the loop $colors = array('red', 'blue', 'green', 'yellow'); foreach ($colors as $color) { echo "Do you like $color?n"; } 0055__aarrrraayyss..pphhpp
  • 27. 05_arrays.php • You can't echo an array directly… • You can walk through an echo or print() line by line • You can use print_r(), this will show you the structure of complex arrays--that output is to the right, and it's handy for learning the structure of an array Array ( [1] => Array ( [sku] => A13412 [quantity] => 10 [item] => Whirly Widgets [price] => .50 ) [2] => Array ( [sku] => A43214 [quantity] => 142 [item] => Widget Nuts [price] => .05 )
  • 28. Multidimensional Arrays • A one dimensional array is a list, a spreadsheet or other columnar data is two dimensional… • Basically, you can make an array of arrays $multiD = array ( "fruits" => array("myfavorite" => "orange", "yuck" => "banana", "yum" => "apple"), "numbers" => array(1, 2, 3, 4, 5, 6), "holes" => array("first", 5 => "second", "third") ); • The structure can be built array by array, or declared with a single statement • You can reference individual elements by nesting: echo "<p>Yes, we have no " . $multiD["fruits"]["yuck"] . " (ok by me).</p>"; 0011aa__aarrrraayyss..pphhpp
  • 29. Getting Data into arrays • You can directly read data into individual array slots via a direct assignment: $pieces[5] = "poulet resistance"; • From a file: • Use the file command to read a delimited file (the delimiter can be any unique char): $pizza = file(./our_pizzas.txt) • Use explode to create an array from a line within a loop: $pieces = explode(" ", $pizza);
  • 30. The Surface • The power of php lies partially in the wealth of functions---for example, the 40+ array functions • array_flip() swaps keys for values • array_count_values() returns an associative array of all values in an array, and their frequency • array_rand() pulls a random element • array_unique() removes duppies • array_walk() applies a user defined function to each element of an array (so you can dice all of a dataset) • count() returns the number of elements in an array • array_search() returns the key for the first match in an array 0088__aarrrraayy__ffuu..pphhpp
  • 31. Using External Data • You can build dynamic pages with just the information in a php script • But where php shines is in building pages out of external data sources, so that the web pages change when the data does • Most of the time, people think of a database like MySQL as the backend, but you can also use text or other files, LDAP, pretty much anything….
  • 32. Standard data files • Normally you'd use a tab delimited file, but you can use pretty much anything as a delimiter • Files get read as arrays, one line per slot • Remember each line ends in n, you should clean this up, and be careful about white space • Once the file is read, you can use explode to break the lines into fields, one at a time, in a loop….
  • 33. Standard data files • You can use trim() to clean white space and returns instead of str_replace() • Notice that this is building an array of arrays $iitteemmss==ffiillee((""..//mmyyddaattaa..ttxxtt""));; ffoorreeaacchh (($$iitteemmss aass $$lliinnee)) {{ $$lliinnee == ssttrr__rreeppllaaccee((""nn"",, """",, $$lliinnee));; $$lliinnee == eexxppllooddee((""tt"",, $$lliinnee));; //// ddoo ssoommeetthhiinngg wwiitthh $$lliinnee aarrrraayy }}
  • 34. Useful string functions • str_replace() • trim(), ltrim(), rtrim() • implode(), explode() • addslashes(), stripslashes() • htmlentities(), html_entity_decode(), htmlspecialchars() • striptags()
  • 35. 06_more_arrays.php • This is a simple script to read and process a text file • The data file is tab delimited and has the column titles as the first line of the file
  • 36. How it works • The script uses the first line to build text labels for the subsequent lines, so that the array elements can be called by the text label • If you add a new column, this script compensates • Text based arrays are not position dependent… • This script could be the basis of a nice function • There are two version of this, calling two different datafiles, but that's the only difference
  • 37. 06a_more_arrays.php • This version shows how to dynamically build a table in the html output
  • 38. Alternative syntax • Applies to if, while, for, foreach, and switch • Change the opening brace to a colon • Change the closing brace to an endxxx statement <?php if ($a == 5): ?> A is equal to 5 <?php endif; ?> <?php if ($a == 5): echo "a equals 5"; echo "..."; else: echo "a is not 5"; endif; ?> 07