SlideShare a Scribd company logo
PHP Introduction
Dr.GINNE M JAMES
Assistant Professor
Department of Computer Science with Data Analytics
Sri Ramakrishna College of Arts and Science
Coimbatore - 641 006
Tamil Nadu, India
1
2
Arrays
Strings and regular expressions
Basic PHP Syntax
CS380
3
Arrays
 Append: use bracket notation without specifying an index
 Element type is not specified; can mix types
$name = array(); # create
$name = array(value0, value1, ..., valueN);
$name[index] # get element value
$name[index] = value; # set element value
$name[] = value; # append
PHP
$a = array(); # empty array (length 0)
$a[0] = 23; # stores 23 at index 0 (length 1)
$a2 = array("some", "strings", "in", "an", "array");
$a2[] = "Ooh!"; # add string to end (at index 5)
PHP
4
Array functions
function name(s) description
count number of elements in the array
print_r print array's contents
array_pop, array_push,
array_shift, array_unshift
using array as a stack/queue
in_array, array_search,
array_reverse,
sort, rsort, shuffle
searching and reordering
array_fill, array_merge,
array_intersect,
array_diff, array_slice, range
creating, filling, filtering
array_sum, array_product,
array_unique,
array_filter, array_reduce
processing elements
CS380
5
Array function example
 the array in PHP replaces many other collections in Java
 list, stack, queue, set, map, ...
$tas = array("MD", "BH", "KK", "HM", "JP");
for ($i = 0; $i < count($tas); $i++) {
$tas[$i] = strtolower($tas[$i]);
}
$morgan = array_shift($tas);
array_pop($tas);
array_push($tas, "ms");
array_reverse($tas);
sort($tas);
$best = array_slice($tas, 1, 2);
PHP
CS380
6
foreach loop
foreach ($array as $variableName) {
...
}
PHP
$fellowship = array(“Frodo", “Sam", “Gandalf",
“Strider", “Gimli", “Legolas", “Boromir");
print “The fellowship of the ring members are: n";
for ($i = 0; $i < count($fellowship); $i++) {
print "{$fellowship[$i]}n";
}
print “The fellowship of the ring members are: n";
foreach ($fellowship as $fellow) {
print "$fellown";
}
PHP
CS380
7
Multidimensional Arrays
<?php $AmazonProducts = array( array(“BOOK",
"Books", 50),
array("DVDs",
“Movies", 15),
array(“CDs", “Music",
20)
);
for ($row = 0; $row < 3; $row++) {
for ($column = 0; $column < 3; $column++) { ?>
<p> | <?= $AmazonProducts[$row]
[$column] ?>
<?php } ?>
</p>
<?php } ?>
PHP
CS380
8
Multidimensional Arrays (cont.)
<?php $AmazonProducts = array( array(“Code” =>“BOOK",
“Description” => "Books", “Price” => 50),
array(“Code” => "DVDs",
“Description” => “Movies", “Price” => 15),
array(“Code” => “CDs",
“Description” => “Music", “Price” => 20)
);
for ($row = 0; $row < 3; $row++) { ?>
<p> | <?= $AmazonProducts[$row][“Code”] ?> | <?=
$AmazonProducts[$row][“Description”] ?> | <?=
$AmazonProducts[$row][“Price”] ?>
</p>
<?php } ?>
PHP
9
String compare functions
Name Function
strcmp compareTo
strstr, strchr find string/char within a string
strpos find numerical position of string
str_replace, substr_replace replace string
 Comparison can be:
 Partial matches
 Others
 Variations with non case sensitive functions
 strcasecmp
CS380
10
String compare functions
examples
$offensive = array( offensive word1, offensive
word2);
$feedback = str_replace($offcolor, “%!@*”,
$feedback);
PHP
$test = “Hello World! n”;
print strpos($test, “o”);
print strpos($test, “o”, 5);
PHP
$toaddress = “feedback@example.com”;
if(strstr($feedback, “shop”)
$toaddress = “shop@example.com”;
else if(strstr($feedback, “delivery”)
$toaddress = “fulfillment@example.com”;
PHP
CS380
11
Regular expressions
[a-z]at #cat, rat, bat…
[aeiou]
[a-zA-Z]
[^a-z] #not a-z
[[:alnum:]]+ #at least one alphanumeric char
(very) *large #large, very very very large…
(very){1, 3} #counting “very” up to 3
^bob #bob at the beginning
com$ #com at the end
PHPRegExp
 Regular expression: a pattern in a piece of text
 PHP has:
 POSIX
 Perl regular expressions
12
CS380
Embedded PHP
13
Printing HTML tags in PHP = bad
style
<?php
print "<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.1//EN"n";
print " "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
n";
print "<html xmlns="http://www.w3.org/1999/xhtml">n";
print " <head>n";
print " <title>Geneva's web page</title>n";
...
for ($i = 1; $i <= 10; $i++) {
print "<p> I can count to $i! </p>n";
}
?>
HTML
 best PHP style is to minimize print/echo statements in
embedded PHP code
 but without print, how do we insert dynamic content into the
page?
CS380
14
PHP expression blocks
 PHP expression block: a small piece of PHP that evaluates and
embeds an expression's value into HTML
 <?= expression ?> is equivalent to:
<?= expression ?>
PHP
<h2> The answer is <?= 6 * 7 ?> </h2>
PHP
The answer is 42
output
<?php print expression; ?>
PHP
15
Expression block example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>CSE 190 M: Embedded PHP</title></head>
<body>
<?php
for ($i = 99; $i >= 1; $i--) {
?>
<p> <?= $i ?> bottles of beer on the wall, <br />
<?= $i ?> bottles of beer. <br />
Take one down, pass it around, <br />
<?= $i - 1 ?> bottles of beer on the wall. </p>
<?php
}
?>
</body>
</html> PHP
CS380
16
Common errors: unclosed braces,
missing = sign
...
<body>
<p>Watch how high I can count:
<?php
for ($i = 1; $i <= 10; $i++) {
?>
<? $i ?>
</p>
</body>
</html> PHP
 if you forget to close your braces, you'll see an error about
'unexpected $end'
 if you forget = in <?=, the expression does not produce any
output
CS380
17
Complex expression blocks
...
<body>
<?php
for ($i = 1; $i <= 3; $i++) {
?>
<h<?= $i ?>>This is a level <?= $i ?>
heading.</h<?= $i ?>>
<?php
}
?>
</body> PHP
This is a level 1 heading.
This is a level 2 heading.
This is a level 3 heading. output
18
CS380
Functions
Advanced PHP Syntax
CS380
19
Functions
function name(parameterName, ..., parameterName) {
statements;
} PHP
function quadratic($a, $b, $c) {
return -$b + sqrt($b * $b - 4 * $a * $c) / (2
* $a);
} PHP
 parameter types and return types are not written
 a function with no return statements implicitly returns NULL
CS380
20
Default Parameter Values
function print_separated($str, $separator = ", ") {
if (strlen($str) > 0) {
print $str[0];
for ($i = 1; $i < strlen($str); $i++) {
print $separator . $str[$i];
}
}
} PHP
print_separated("hello"); # h, e, l, l, o
print_separated("hello", "-"); # h-e-l-l-o
PHP
 if no value is passed, the default will be used
CS380
21
PHP Arrays Ex. 1
 Arrays allow you to assign multiple values to one variable. For
this PHP exercise, write an array variable of weather conditions
with the following values: rain, sunshine, clouds, hail, sleet, snow,
wind. Using the array variable for all the weather conditions,
echo the following statement to the browser:
We've seen all kinds of weather this month. At the beginning of the
month, we had snow and wind. Then came sunshine with a few
clouds and some rain. At least we didn't get any hail or sleet.
 Don't forget to include a title for your page, both in the header
and on the page itself.
CS380
22
PHP Arrays Ex. 2
 For this exercise, you will use a list of ten of the largest cities in
the world. (Please note, these are not the ten largest, just a
selection of ten from the largest cities.) Create an array with the
following values: Tokyo, Mexico City, New York City, Mumbai,
Seoul, Shanghai, Lagos, Buenos Aires, Cairo, London.
 Print these values to the browser separated by commas, using a
loop to iterate over the array. Sort the array, then print the
values to the browser in an unordered list, again using a loop.
 Add the following cities to the array: Los Angeles, Calcutta,
Osaka, Beijing. Sort the array again, and print it once more to
the browser in an unordered list.

More Related Content

PPTX
Presentaion
CBRIARCSC
 
PPTX
07 php
CBRIARCSC
 
PPTX
overview of php php basics datatypes arrays
yatakonakiran2
 
PPTX
07-PHP.pptx
ShishirKantSingh1
 
PPTX
07-PHP.pptx
GiyaShefin
 
PPTX
Php Syntax Basics in one single course in nutshell
binzbinz3
 
PPTX
06-PHPIntroductionserversicebasicss.pptx
20521742
 
PPT
introduction to php web programming 2024.ppt
idaaryanie
 
Presentaion
CBRIARCSC
 
07 php
CBRIARCSC
 
overview of php php basics datatypes arrays
yatakonakiran2
 
07-PHP.pptx
ShishirKantSingh1
 
07-PHP.pptx
GiyaShefin
 
Php Syntax Basics in one single course in nutshell
binzbinz3
 
06-PHPIntroductionserversicebasicss.pptx
20521742
 
introduction to php web programming 2024.ppt
idaaryanie
 

Similar to PHP (Hypertext Preprocessor) is a popular open-source server-side scripting language (20)

PPTX
Php
Richa Goel
 
PPTX
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
PPTX
08 php-files
hoangphuc2587
 
PPT
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
PPT
PHP complete reference with database concepts for beginners
Mohammed Mushtaq Ahmed
 
PDF
Web app development_php_04
Hassen Poreya
 
PPTX
Php by shivitomer
Shivi Tomer
 
PPTX
Mdst 3559-02-15-php
Rafael Alvarado
 
PPT
php41.ppt
Nishant804733
 
PPT
php-I-slides.ppt
SsewankamboErma
 
PPT
PHP InterLevel.ppt
NBACriteria2SICET
 
PPTX
Php
Yoga Raja
 
PPT
Php course-in-navimumbai
vibrantuser
 
PPT
PHP and MySQL with snapshots
richambra
 
PDF
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
pkaviya
 
PDF
lab4_php
tutorialsruby
 
PDF
lab4_php
tutorialsruby
 
PDF
Php Tutorials for Beginners
Vineet Kumar Saini
 
PDF
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
08 php-files
hoangphuc2587
 
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
PHP complete reference with database concepts for beginners
Mohammed Mushtaq Ahmed
 
Web app development_php_04
Hassen Poreya
 
Php by shivitomer
Shivi Tomer
 
Mdst 3559-02-15-php
Rafael Alvarado
 
php41.ppt
Nishant804733
 
php-I-slides.ppt
SsewankamboErma
 
PHP InterLevel.ppt
NBACriteria2SICET
 
Php course-in-navimumbai
vibrantuser
 
PHP and MySQL with snapshots
richambra
 
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
pkaviya
 
lab4_php
tutorialsruby
 
lab4_php
tutorialsruby
 
Php Tutorials for Beginners
Vineet Kumar Saini
 
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
Ad

More from jinijames109 (14)

PPTX
Number_system_simple_presentation_1.pptx
jinijames109
 
PPTX
Logic___Gates__Simple__Presentation.pptx
jinijames109
 
PPTX
Instruction_Set_DFA_simple_Presentation.pptx
jinijames109
 
PPTX
Flip_Flops_in_DFA_simple_Presentation.pptx
jinijames109
 
PPTX
Encoders_and_Decoders_Pre_sentation.pptx
jinijames109
 
PPTX
Disk_Controller_Simple_Presentation.pptx
jinijames109
 
PPTX
Counters_Simple_Presentation_Digital_Fundamentals.pptx
jinijames109
 
PPTX
Working of File System: An Overview in detail
jinijames109
 
PPT
Understanding PHP Functions: A Comprehensive Guide to Creating
jinijames109
 
PPTX
tructured Query Language (SQL) is a standardized programming language
jinijames109
 
PPTX
MySQL: An Open-Source Relational Database Engine for Fast, Reliable, and Scal...
jinijames109
 
PPTX
Understanding Shell Configuration in Linux
jinijames109
 
PPTX
Transmission Control Protocol (TCP) Basics
jinijames109
 
PPTX
Understanding the OSI Model: A Layered Approach
jinijames109
 
Number_system_simple_presentation_1.pptx
jinijames109
 
Logic___Gates__Simple__Presentation.pptx
jinijames109
 
Instruction_Set_DFA_simple_Presentation.pptx
jinijames109
 
Flip_Flops_in_DFA_simple_Presentation.pptx
jinijames109
 
Encoders_and_Decoders_Pre_sentation.pptx
jinijames109
 
Disk_Controller_Simple_Presentation.pptx
jinijames109
 
Counters_Simple_Presentation_Digital_Fundamentals.pptx
jinijames109
 
Working of File System: An Overview in detail
jinijames109
 
Understanding PHP Functions: A Comprehensive Guide to Creating
jinijames109
 
tructured Query Language (SQL) is a standardized programming language
jinijames109
 
MySQL: An Open-Source Relational Database Engine for Fast, Reliable, and Scal...
jinijames109
 
Understanding Shell Configuration in Linux
jinijames109
 
Transmission Control Protocol (TCP) Basics
jinijames109
 
Understanding the OSI Model: A Layered Approach
jinijames109
 
Ad

Recently uploaded (20)

PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Software Development Methodologies in 2025
KodekX
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Software Development Company | KodekX
KodekX
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 

PHP (Hypertext Preprocessor) is a popular open-source server-side scripting language

  • 1. PHP Introduction Dr.GINNE M JAMES Assistant Professor Department of Computer Science with Data Analytics Sri Ramakrishna College of Arts and Science Coimbatore - 641 006 Tamil Nadu, India 1
  • 2. 2 Arrays Strings and regular expressions Basic PHP Syntax
  • 3. CS380 3 Arrays  Append: use bracket notation without specifying an index  Element type is not specified; can mix types $name = array(); # create $name = array(value0, value1, ..., valueN); $name[index] # get element value $name[index] = value; # set element value $name[] = value; # append PHP $a = array(); # empty array (length 0) $a[0] = 23; # stores 23 at index 0 (length 1) $a2 = array("some", "strings", "in", "an", "array"); $a2[] = "Ooh!"; # add string to end (at index 5) PHP
  • 4. 4 Array functions function name(s) description count number of elements in the array print_r print array's contents array_pop, array_push, array_shift, array_unshift using array as a stack/queue in_array, array_search, array_reverse, sort, rsort, shuffle searching and reordering array_fill, array_merge, array_intersect, array_diff, array_slice, range creating, filling, filtering array_sum, array_product, array_unique, array_filter, array_reduce processing elements
  • 5. CS380 5 Array function example  the array in PHP replaces many other collections in Java  list, stack, queue, set, map, ... $tas = array("MD", "BH", "KK", "HM", "JP"); for ($i = 0; $i < count($tas); $i++) { $tas[$i] = strtolower($tas[$i]); } $morgan = array_shift($tas); array_pop($tas); array_push($tas, "ms"); array_reverse($tas); sort($tas); $best = array_slice($tas, 1, 2); PHP
  • 6. CS380 6 foreach loop foreach ($array as $variableName) { ... } PHP $fellowship = array(“Frodo", “Sam", “Gandalf", “Strider", “Gimli", “Legolas", “Boromir"); print “The fellowship of the ring members are: n"; for ($i = 0; $i < count($fellowship); $i++) { print "{$fellowship[$i]}n"; } print “The fellowship of the ring members are: n"; foreach ($fellowship as $fellow) { print "$fellown"; } PHP
  • 7. CS380 7 Multidimensional Arrays <?php $AmazonProducts = array( array(“BOOK", "Books", 50), array("DVDs", “Movies", 15), array(“CDs", “Music", 20) ); for ($row = 0; $row < 3; $row++) { for ($column = 0; $column < 3; $column++) { ?> <p> | <?= $AmazonProducts[$row] [$column] ?> <?php } ?> </p> <?php } ?> PHP
  • 8. CS380 8 Multidimensional Arrays (cont.) <?php $AmazonProducts = array( array(“Code” =>“BOOK", “Description” => "Books", “Price” => 50), array(“Code” => "DVDs", “Description” => “Movies", “Price” => 15), array(“Code” => “CDs", “Description” => “Music", “Price” => 20) ); for ($row = 0; $row < 3; $row++) { ?> <p> | <?= $AmazonProducts[$row][“Code”] ?> | <?= $AmazonProducts[$row][“Description”] ?> | <?= $AmazonProducts[$row][“Price”] ?> </p> <?php } ?> PHP
  • 9. 9 String compare functions Name Function strcmp compareTo strstr, strchr find string/char within a string strpos find numerical position of string str_replace, substr_replace replace string  Comparison can be:  Partial matches  Others  Variations with non case sensitive functions  strcasecmp
  • 10. CS380 10 String compare functions examples $offensive = array( offensive word1, offensive word2); $feedback = str_replace($offcolor, “%!@*”, $feedback); PHP $test = “Hello World! n”; print strpos($test, “o”); print strpos($test, “o”, 5); PHP $toaddress = “[email protected]”; if(strstr($feedback, “shop”) $toaddress = “[email protected]”; else if(strstr($feedback, “delivery”) $toaddress = “[email protected]”; PHP
  • 11. CS380 11 Regular expressions [a-z]at #cat, rat, bat… [aeiou] [a-zA-Z] [^a-z] #not a-z [[:alnum:]]+ #at least one alphanumeric char (very) *large #large, very very very large… (very){1, 3} #counting “very” up to 3 ^bob #bob at the beginning com$ #com at the end PHPRegExp  Regular expression: a pattern in a piece of text  PHP has:  POSIX  Perl regular expressions
  • 13. 13 Printing HTML tags in PHP = bad style <?php print "<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"n"; print " "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> n"; print "<html xmlns="http://www.w3.org/1999/xhtml">n"; print " <head>n"; print " <title>Geneva's web page</title>n"; ... for ($i = 1; $i <= 10; $i++) { print "<p> I can count to $i! </p>n"; } ?> HTML  best PHP style is to minimize print/echo statements in embedded PHP code  but without print, how do we insert dynamic content into the page?
  • 14. CS380 14 PHP expression blocks  PHP expression block: a small piece of PHP that evaluates and embeds an expression's value into HTML  <?= expression ?> is equivalent to: <?= expression ?> PHP <h2> The answer is <?= 6 * 7 ?> </h2> PHP The answer is 42 output <?php print expression; ?> PHP
  • 15. 15 Expression block example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title>CSE 190 M: Embedded PHP</title></head> <body> <?php for ($i = 99; $i >= 1; $i--) { ?> <p> <?= $i ?> bottles of beer on the wall, <br /> <?= $i ?> bottles of beer. <br /> Take one down, pass it around, <br /> <?= $i - 1 ?> bottles of beer on the wall. </p> <?php } ?> </body> </html> PHP
  • 16. CS380 16 Common errors: unclosed braces, missing = sign ... <body> <p>Watch how high I can count: <?php for ($i = 1; $i <= 10; $i++) { ?> <? $i ?> </p> </body> </html> PHP  if you forget to close your braces, you'll see an error about 'unexpected $end'  if you forget = in <?=, the expression does not produce any output
  • 17. CS380 17 Complex expression blocks ... <body> <?php for ($i = 1; $i <= 3; $i++) { ?> <h<?= $i ?>>This is a level <?= $i ?> heading.</h<?= $i ?>> <?php } ?> </body> PHP This is a level 1 heading. This is a level 2 heading. This is a level 3 heading. output
  • 19. CS380 19 Functions function name(parameterName, ..., parameterName) { statements; } PHP function quadratic($a, $b, $c) { return -$b + sqrt($b * $b - 4 * $a * $c) / (2 * $a); } PHP  parameter types and return types are not written  a function with no return statements implicitly returns NULL
  • 20. CS380 20 Default Parameter Values function print_separated($str, $separator = ", ") { if (strlen($str) > 0) { print $str[0]; for ($i = 1; $i < strlen($str); $i++) { print $separator . $str[$i]; } } } PHP print_separated("hello"); # h, e, l, l, o print_separated("hello", "-"); # h-e-l-l-o PHP  if no value is passed, the default will be used
  • 21. CS380 21 PHP Arrays Ex. 1  Arrays allow you to assign multiple values to one variable. For this PHP exercise, write an array variable of weather conditions with the following values: rain, sunshine, clouds, hail, sleet, snow, wind. Using the array variable for all the weather conditions, echo the following statement to the browser: We've seen all kinds of weather this month. At the beginning of the month, we had snow and wind. Then came sunshine with a few clouds and some rain. At least we didn't get any hail or sleet.  Don't forget to include a title for your page, both in the header and on the page itself.
  • 22. CS380 22 PHP Arrays Ex. 2  For this exercise, you will use a list of ten of the largest cities in the world. (Please note, these are not the ten largest, just a selection of ten from the largest cities.) Create an array with the following values: Tokyo, Mexico City, New York City, Mumbai, Seoul, Shanghai, Lagos, Buenos Aires, Cairo, London.  Print these values to the browser separated by commas, using a loop to iterate over the array. Sort the array, then print the values to the browser in an unordered list, again using a loop.  Add the following cities to the array: Los Angeles, Calcutta, Osaka, Beijing. Sort the array again, and print it once more to the browser in an unordered list.

Editor's Notes

  • #5: Maybe delete the comments that give out the output # ("md", "bh", "kk", "hm", "jp") # ("bh", "kk", "hm") # ("bh", "kk", "hm", "ms") # ("ms", "hm", "kk", "bh") # ("bh", "hm", "kk", "ms") # ("hm", "kk")
  • #6: One bad thing with foreach: you cannot change the value of the variable after “as”, you can just assign it a value, it does not have the value in the table
  • #7: Maybe delete the comments that give out the output
  • #14: useful for embedding a small amount of PHP (a variable's or expression's value) in a large block of HTML without having to switch to "PHP-mode"