Basic PHP Syntax: Arrays Strings and Regular Expressions
Basic PHP Syntax: Arrays Strings and Regular Expressions
Basic PHP Syntax: Arrays Strings and Regular Expressions
Arrays
Strings and regular expressions
CS380
Arrays
2
CS380
Multidimensional Arrays
7
(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
CS380
String compare functions
8
Name Function
strcmp compareTo
find string/char within a
strstr, strchr
string
find numerical position of
strpos
string
str_replace,
Comparison can be: replace string
substr_replace
Partial matches
Others
Variations with non case sensitive
functions
String compare functions
9
examples
$offensive = array( offensive word1, offensive
word2);
$feedback = str_replace($offcolor, %!@*,
$feedback);
PHP
$toaddress = [email protected];
if(strstr($feedback, shop)
$toaddress = [email protected];
else if(strstr($feedback, delivery)
$toaddress = [email protected];
CS380 PHP
Regular expressions
10
CS380
Printing HTML tags in PHP =
12
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?
PHP expression blocks
13
The answer is 42
output
...
<body>
<?php
for ($i = 1; $i <= 3; $i++) {
?>
<h<?= $i ?>>This is a level <?= $i ?>
heading.</h<?= $i ?>>
<?php
}
?>
</body> PHP
CS380
Functions
18
CS380
Default Parameter Values
19
print_separated("hello"); # h, e, l, l, o
print_separated("hello", "-"); # h-e-l-l-o
PHP
CS380
PHP Arrays Ex. 1
20