0% found this document useful (0 votes)
13 views25 pages

Web Dev Final Book Page Num-31-55

Uploaded by

aryanjsr432
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views25 pages

Web Dev Final Book Page Num-31-55

Uploaded by

aryanjsr432
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

int $length = NULL [, bool array_splice

$preserve_keys =
• —Remove a portion of the array and
false ]] ) replace

• array_slice() returns the sequence of it with something else

elements from the array array as Description


specified by
• array array_splice ( array &$input ,
the offset and length parameters. int $offset

• <?php [, int $length = 0 [, mixed

$input = array("a", "b", "c", "d", "e"); $replacement ]] )

$output = array_slice($input, 2); • Removes the elements designated by


offset
// returns "c", "d", and "e"
and length from the input array, and
$output = array_slice($input,-2, 1); //
replaces
returns "d"
them with the elements of the
$output = array_slice($input, 0, 3); //
replacement
returns "a", "b", and "c"
array, if supplied.
// note the differences in the array keys
• <?php
print_r(array_slice($input, 2,-1));
$input = array("red", "green", "blue",
print_r(array_slice($input, 2,-1,
"yellow");
true));
$a=array_splice($input, 2);
?>
// $input is now array("red", "green")
Output:
$input = array("red", "green", "blue",
Array (
"yellow");
[0] => c
array_splice($input, 1,-1);
[1] => d )
// $input is now array("red", "yellow")
Array (
$input = array("red", "green", "blue",
[2] => c "yellow");

[3] => d )

31
array_splice($input, 1, count($input), print_r($queue);
"orange");
?>
// $input is now array("red", "orange")
• The above example will output:
array_unshift
• Array ( [0] => apple [1] =>
• —Prependone or more elements to raspberry [2] =>
the
orange [3] => banana )
beginning of an array
array_values
Description
• —Return all the values of an array
• int array_unshift ( array &$array ,
Description
mixed
• array array_values ( array $input )
mixed
• array_values() returns all the values
$... ] )
from the
$var [,
input array and indexes numerically
• array_unshift() prepends passed the array.
elements to the
• <?php
front of the array. Note that the list of
$array = array("size" => "XL",
elements
"color" => "gold"
is prepended as a whole, so that the
);
prepended
print_r(array_values($array));
elements stay in the same order. All
numerical ?>
array keys will be modified to start • The above example will output:
counting from
• Array ( [0] => XL [1] => gold )
zero while literal keys won't be
touched. arsort

• <?php • —Sort an array in reverse order and


maintain
$queue = array("orange", "banana");
index association
array_unshift($queue, "apple",
"raspberry"); Description

32
• bool arsort ( array &$array [, int • This function sorts an array such that
$sort_flags = array

SORT_REGULAR ] ) indices maintain their correlation with


the array
• This function sorts an array such that
array elements they are associated with. This
is used
indices maintain their correlation with
the mainly when sorting associative arrays
where the
array elements they are associated
with. actual element order is significant.

• <?php • <?php

$fruits = array("d" => "lemon", "a" $fruits = array("d" => "lemon", "a"
=> "orange", " => "orange", "

b" => "banana", "c" => "apple"); b" => "banana", "c" => "apple");

arsort($fruits); asort($fruits);

foreach ($fruits as $key => $val) { foreach ($fruits as $key => $val) {

echo "$key = $val\n"; echo "$key = $val\n";

} }

?> ?>

• The above example will output: • The above example will output:

• a = orange d = lemon b = banana c • c = apple b = banana d = lemon a =


= apple orange

asort count

• —Sort an array and maintain index • —Count all elements in an array, or


association
something in an object
Description
Description
• bool asort ( array &$array [, int
• int count ( mixed
$sort_flags =
$var [, int $mode =
SORT_REGULAR ] )

33
COUNT_NORMAL ] ) $varname [, mixed

• Counts all elements in an array, or $... ] )


something
, this is not really a function, but a
in an object.
language construct. list() is used to
• <?php assign a

$a[0] = 1; list of variables in one operation.

$a[1] = 3; • <?php

$a[2] = 5; $info = array('coffee', 'brown',


'caffeine');
$result = count($a);
// Listing all the variables
// $result == 3
list($drink, $color, $power) = $info;
$b[0] = 7;
echo "$drink is $color and $power
$b[5] = 9;
makes it special.\n";
$b[10] = 11;
// Listing some of them
$result = count($b);
list($drink, , $power) = $info;
// $result == 3
echo "$drink has $power.\n";
$result = count(null);
// Or let's skip to only the third one
// $result == 0
list( , , $power) = $info;
$result = count(false);
echo "I need $power!\n";
// $result == 1
// list() doesn't work with strings
?>
list($bar) = "abcde";
list
var_dump($bar); // NULL
• —Assign variables as if they were an
sort
array
• —Sort an array
Description
Description
• array list ( mixed

• Like array()

34
• bool sort ( array &$array [, int number
$sort_flags =
$start , mixed
SORT_REGULAR ] )
$step = 1 ] )
• This function sorts an array.
$limit [,
Elements will be
• Create an array containing a range of
arranged from lowest to highest when
this elements.
function has completed. • <?php
• <?php // array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12)
$fruits = array("lemon", "orange",
"banana", "apple"); foreach (range(0, 12) as $number) {
sort($fruits); }
foreach ($fruits as $key => $val) { echo $number;
} // The step parameter was introduced
in 5.0.0
echo "fruits[" . $key . "] = " . $val .
"\n"; // array(0, 10, 20, 30, 40, 50, 60, 70,
80, 90, 100)
?>
foreach (range(0, 100, 10) as
• The above example will output:
$number) {
• fruits[0] = apple fruits[1] = banana
}
fruits[2] = lemon
echo $number;
fruits[3] = orange
// Use of character sequences
range
introduced in 4.1.0
• —Create an array containing a
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
range of
'i');
elements
foreach (range('a', 'i') as $letter) {
• Description
}
• array range ( mixed
echo $letter;

35
// array('c', 'b', 'a'); • Note: If the search parameter is a
string and the type parameter is
foreach (range('c', 'a') as $letter) {
set to TRUE, the search is case-
}
sensitive.
echo $letter;
• Syntax
?>
• in_array(search,array,type)
shuffle

• —Shuffle an array
Parameter Description
• Description
• search-Specifies the what to search
• bool shuffle ( array &$array ) for

• This function shuffles (randomizes • array. Specifies the array to search


the order
• typeOptional. If this parameter is set
of the elements in) an array. to TRUE, the in_array()

• <?php function searches for the search-string


and specific type in the
$numbers = range(1, 20);
array.
shuffle($numbers);
• <?php
foreach ($numbers as $number) {
$people = array("Peter", "Joe",
echo "$number "; "Glenn", "Cleveland");
} if (in_array("Glenn", $people))
?> {
• sizeof — Alias of count() echo "Match found";
Description }
• This function is an alias of: count() else
. {
• The in_array() function searches an echo "Match not found";
array for a specific value.
}

36
?>

html

Copy code

2.2 PHP Functions <html>

What is a Function? <body>

A function is a block of code designed <?php


to accomplish a specific task. A
// Defining function: printHello
function is executed when it is called. It
may return a value or may not return function printHello()
any value.
{

echo "Hello";
A Function That Does Not Return a
Value }

To define a function that does not // Calling the function: printHello


return a value, you can use the printHello();
following syntax:
?>

</body>
php
</html>
Copy code
A Function That Returns a Value
function function_name()
When you want to get the value
{ generated from a function to be used
// statements elsewhere in your code, you need to
define a function that can return a
} value. The return keyword is used to
return the value of the function to
Note: The name of the function must
another function or code block that
start with a letter or an underscore; it
calls it.
cannot start with a number.

Syntax:
Example:

37
</body>

php </html>

Copy code Function Parameters

function function_name() Parameters are values passed to the


function. You can pass more than one
{
parameter to the function by separating
// statements them with commas.

return value;

} Example:

Example:
html

html Copy code

Copy code <html>

<html> <body>

<body> <?php

<?php // Defining function: printName

// Defining function: sum function printName($name)

function sum() {

{ echo "Hello " . $name;

$s = 10 + 20; }

return $s; // Calling the function: printName

} printName("Khorn Channa");

// Calling the function: sum ?>

$total = sum(); </body>

echo "Total = " . $total; </html>

?> 2.3 PHP - GET & POST Methods

38
There are two ways the browser client http://www.test.com/index.htm?name1
can send information to the web server: =value1&name2=value2

The POST Method The GET method produces a long


string that appears in your server logs
Before the browser sends the
and in the browser's Location box.
information, it encodes it using a
scheme called URL encoding. In this The GET method is restricted to send
scheme, name/value pairs are joined up to 1024 characters only.
with equal signs, and different pairs
Never use the GET method if you have
are separated by the ampersand:
passwords or other sensitive
information to send to the server.

makefile GET can't be used to send binary data,


like images or Word documents, to the
Copy code
server.
name1=value1&name2=value2&name
The data sent by the GET method can
3=value3
be accessed using the
Spaces are removed and replaced with QUERY_STRING environment
the + character, and any other non- variable.
alphanumeric characters are replaced
PHP provides the $_GET associative
with hexadecimal values. After the
array to access all the sent information
information is encoded, it is sent to the
using the GET method.
server.
Example of GET Method

Try out the following example by


The GET Method
putting the source code in test.php
The GET method sends the encoded script.
user information appended to the page
request. The page and the encoded
information are separated by the ? php
character.
Copy code

<?php
arduino
if ($_GET["name"] || $_GET["age"]) {
Copy code
echo "Welcome " . $_GET['name'] .
"<br />";

39
echo "You are " . $_GET['age'] . " The POST method can be used to send
years old."; ASCII as well as binary data.

exit(); The data sent by the POST method goes


through HTTP headers, so security
}
depends on the HTTP protocol. By
?> using Secure HTTP, you can ensure
that your information is secure.
<html>
PHP provides the $_POST associative
<body> array to access all the sent information
<form action="<?php $_PHP_SELF using the POST method.
?>" method="GET"> Example of POST Method
Name: <input type="text" Try out the following example by
name="name" /> putting the source code in test.php
Age: <input type="text" script.
name="age" />

<input type="submit" /> php


</form> Copy code
</body> <?php
</html> if ($_POST["name"] ||
It will produce the following result: $_POST["age"]) {

if (preg_match("/[^A-Za-z'-]/",
$_POST['name'])) {
The POST Method
die("Invalid name; name should
The POST method transfers be alphabetical.");
information via HTTP headers. The
information is encoded as described in }
the case of the GET method and put echo "Welcome " . $_POST['name'] .
into a header called QUERY_STRING. "<br />";

echo "You are " . $_POST['age'] . "


The POST method does not have any years old.";
restriction on the data size to be sent. exit();

40
} php

?> <?php

<html> if ($_REQUEST["name"] ||
$_REQUEST["age"]) {
<body>
echo "Welcome " .
<form action="<?php $_PHP_SELF
$_REQUEST['name'] . "<br />";
?>" method="POST">
echo "You are " .
Name: <input type="text"
$_REQUEST['age'] . " years old.";
name="name" />
exit();
Age: <input type="text"
name="age" /> }

<input type="submit" /> ?>

</form> <html>

</body> <body>

</html> <form action="<?php $_PHP_SELF


?>" method="POST">
It will produce the following result:
Name: <input type="text"
The $_REQUEST Variable
name="name" />
The PHP $_REQUEST variable
Age: <input type="text"
contains the contents of both $_GET,
name="age" />
$_POST, and $_COOKIE. We will
discuss the $_COOKIE variable when <input type="submit" />
we explain cookies. The PHP
</form>
$_REQUEST variable can be used to
get the result from form data sent with </body>
both the GET and POST methods.
</html>

Here, the $_PHP_SELF variable


Example of $_REQUEST Variable contains the name of the script in which
it is being called.
Try out the following example by
putting the source code in test.php
script.
It will produce the following result:

41
PHP Form Introduction $gender =
test_input($_POST["gender"]);
Example
}
Below is an example that shows the
form with some specific actions using
the POST method.
function test_input($data) {
Html
$data = trim($data);

$data = stripslashes($data);
<html>
$data =
<head> htmlspecialchars($data);

<title>PHP Form Validation</title> return $data;

</head> }

<body> ?>

<?php

// Define variables and set to <h2>Classes Registration</h2>


empty values

$name = $email = $gender =


<form method="post"
$comment = $website = "";
action="/view.php">

<table>
if
<tr>
($_SERVER["REQUEST_METHOD"]
== "POST") { <td>Name:</td>
$name = <td><input type="text"
test_input($_POST["name"]); name="name"></td>
$email = </tr>
test_input($_POST["email"]);
<tr>
$website =
test_input($_POST["website"]); <td>E-mail:</td>

$comment = <td><input type="text"


test_input($_POST["comment"]); name="email"></td>

42
</tr> </tr>

<tr> </table>

<td>Specific Time:</td> </form>

<td><input type="text"
name="website"></td>
<?php
</tr>
echo "<h2>Your Given Details
<tr> Are:</h2>";

<td>Class details:</td> echo $name;

<td><textarea echo "<br>";


name="comment" rows="5"
echo $email;
cols="40"></textarea></td>
echo "<br>";
</tr>
echo $website;
<tr>
echo "<br>";
<td>Gender:</td>
echo $comment;
<td>
echo "<br>";
<input type="radio"
name="gender" echo $gender;
value="female">Female
?>
<input type="radio"
name="gender" value="male">Male </body>

</td> </html>

</tr>

<tr>

<td>

<input type="submit" PHP String Built-in Functions


name="submit" value="Submit"> Introduction to String Functions
</td> String functions are essential in PHP
for manipulating and processing text.

43
PHP provides a wide range of built-in echo $newText; // Outputs: 'I love
string functions. coding'

Some commonly used string functions 3. strpos(): Find Position of Substring


include:
Description: Finds the position of the
strlen() first occurrence of a substring in a
string.
str_replace()
Example:
strpos()
php
substr()
Copy code
strtoupper() and strtolower()
$text = 'Hello World';
Commonly Used String Functions
$pos = strpos($text, 'World');
1. strlen(): Get the Length of a String
echo $pos; // Outputs: 6 (position of
Description: Returns the length of a
'World' starts at index 6)
string (number of characters).
4. substr(): Extract a Part of a String
Example:
Description: Returns a part of a string
php
starting at a specified position.
Copy code
Example:
$str = 'Hello World';
php
echo strlen($str); // Outputs: 11
Copy code
2. str_replace(): Replace Substring
$text = 'Hello World';
Description: Replaces all occurrences
$part = substr($text, 6, 5);
of a substring with another substring.
echo $part; // Outputs: 'World' (5
Example:
characters starting from position 6)
php
5. strtoupper(): Change Case to
Copy code Uppercase

$text = 'I love PHP'; Description: Converts a string to


uppercase.
$newText = str_replace('PHP',
'coding', $text); Example:

44
php Description: Converts the first
character of a string to lowercase.
Copy code
Example:
$text = 'Hello World';
php
echo strtoupper($text); // Outputs:
'HELLO WORLD' Copy code

6. strtolower(): Change Case to $text = 'Hello World';


Lowercase
echo lcfirst($text); // Outputs: 'hello
Description: Converts a string to World'
lowercase.
9. ucwords(): Capitalize the First
Example: Character of Each Word

php Description: Capitalizes the first


character of each word.
Copy code
Example:
$text = 'HELLO WORLD';
php
echo strtolower($text); // Outputs:
'hello world' Copy code

7. ucfirst(): Capitalize the First $text = 'hello world';


Character
echo ucwords($text); // Outputs: 'Hello
Description: Capitalizes the first World'
character of a string.
10. strrev(): Reverse a String
Example:
Description: Reverses a string.
php
Example:
Copy code
php
$text = 'hello world';
Copy code
echo ucfirst($text); // Outputs: 'Hello
$text = 'hello';
world'
echo strrev($text); // Outputs: 'olleh'
8. lcfirst(): Lowercase the First
Character 11. explode(): Split a String into an
Array

45
Description: Splits a string into an $text = ' Hello World ';
array by a delimiter.
echo trim($text); // Outputs: 'Hello
Example: World'

php 14. ltrim(): Remove Whitespace from


the Beginning
Copy code
Description: Removes whitespace from
$text = 'apple,banana,cherry';
the beginning of a string.
$fruits = explode(',', $text);
Example:
print_r($fruits); // Outputs: Array([0]
php
=> apple, [1] => banana, [2] =>
cherry) Copy code

12. implode(): Join Array Elements $text = ' Hello World';


into a String
echo ltrim($text); // Outputs: 'Hello
Description: Joins array elements into World'
a string.
15. rtrim(): Remove Whitespace from
Example: the End

php Description: Removes whitespace from


the end of a string.
Copy code
Example:
$fruits = ['apple', 'banana', 'cherry'];
php
$text = implode(',', $fruits);
Copy code
echo $text; // Outputs:
'apple,banana,cherry' $text = 'Hello World ';

13. trim(): Remove Whitespace from echo rtrim($text); // Outputs: 'Hello


the Start and End World'

Description: Removes whitespace from 16. str_split(): Split a String into an


the start and end of a string. Array by a Specific Length

Example: Description: Splits a string into an


array by a specific length.
php
Example:
Copy code

46
php Definition

Copy code Server-side programming involves


writing programs in various web
$text = 'hello';
programming languages/frameworks
$chars = str_split($text, 2); to:

print_r($chars); // Outputs: Array([0] Dynamically edit, change, or add


=> 'he', [1] => 'll', [2] => 'o') content to a web page.

3. PHP Server-Side Basics Respond to user queries or data


submitted from HTML forms.

Access data or databases and return


URLs and Web Servers the results to a browser.
3.1 Overview of URL Structure Customize web pages for individual
A typical URL format: users.
http://server/path/file Provide security since server code
Process when a URL is entered in a cannot be viewed from a browser.
browser: Examples of Server-Side Languages
The computer looks up the server's IP PHP, Java/JSP, Ruby on Rails,
address using DNS. ASP.NET, Python, Perl, etc.
The browser connects to that IP Web Server Functionality
address and requests the specified file.
The web server contains software that
The web server software (e.g., Apache) allows it to run server-side programs
retrieves the file from the server's local and sends back their output as
file system. responses to web requests. Each
The server sends the file's contents language/framework has its pros and
back to the browser. cons, and in this context, we use PHP.

Example of URL Request What is PHP?

For instance, the URL PHP stands for "PHP Hypertext


http://www.facebook.com/home.php Preprocessor."
tells the server to run the program A server-side scripting language used
home.php and return its output. to create dynamic web pages:
Server-Side Web Programming

47
Provides different content depending Syntax: $variable_name = value;
on the context.
Example:
Interfaces with services such as
php
databases and email.
Copy code
Authenticates users and processes form
information. $user_name = "ram80";
PHP code can be embedded within $age = 16;
HTML code.
$drinking_age = $age + 5;
Lifecycle of a PHP Web Request
$this_class_rocks = TRUE;
User's computer requests a .php file.
Variable names are case-sensitive,
The server processes the request and always begin with $, and are implicitly
returns the output. declared by assignment.
Basic PHP Syntax Data Types
PHP Syntax Template Basic types include: int, float, boolean,
string, array, object, NULL.
Code between <?php and ?> is
executed as PHP. PHP automatically converts between
types in many cases.
Everything outside these tags is output
as pure HTML.

Example of PHP Syntax Type Casting


php Use (type) to cast variables:
Copy code php
<?php Copy code
print "Hello, world!"; $age = (int) "21";
?> PHP Operators
Output: Hello, world! Arithmetic Operators
PHP Variables Operators: +, -, *, /, %, ., ++
Variable Declaration Assignment Operators: =, +=, -=, *=,
/=, %=, .=

48
Comments Object Data Type

Single-line comments: # or // php

Multi-line comments: /* comment */ class Car {

PHP Data Types Overview public $color;

String Data Type public function __construct($color) {

php $this->color = $color;

$string_var = "Hello, World!"; }

echo $string_var; // Outputs: Hello, public function get_color() {


World!
return $this->color;
Integer Data Type
}
php
}
$int_var = 42;
$my_car = new Car("red");
echo $int_var; // Outputs: 42
echo $my_car->get_color(); //
Float Data Type Outputs: red

php NULL Data Type

$float_var = 3.14; php

echo $float_var; // Outputs: 3.14 $null_var = NULL;

Boolean Data Type echo $null_var; // Outputs nothing

php Resource Data Type

$bool_var = true; php

echo $bool_var; // Outputs: 1 (true) $file = fopen("example.txt", "r");

Array Data Type echo fread($file,


filesize("example.txt"));
php
fclose($file);
$array_var = array("apple", "banana",
"cherry"); php

echo $array_var[0]; // Outputs: apple $name = "Stefanie Hatcher";

49
$length = strlen($name); // 15 // statements;

$index = strpos($name, "e"); // 2 }

$first = substr($name, 9, 5); // "Hatch" For Loop

$name = strtoupper($name); // php


"STEFANIE HATCHER"
Copy code
3.2 Interpreted Strings
for ($i = 0; $i < 10; $i++) {
Variable Interpolation in Strings
print "$i squared is " . $i * $i . ".\n";
Strings within double quotes (")
}
interpret variables:
While Loop
php
php
$age = 16;
Copy code
print "You are $age years old."; // You
are 16 years old. while (condition) {
Strings within single quotes (') do not // statements;
interpret variables:
}
php
Do-While Loop
Copy code
php
print 'You are $age years old.'; // You
are $age years old. Copy code

Control Structures do {

If/Else Statement // statements;

php } while (condition);

if (condition) { Math Operations and Functions

// statements; Common functions include: abs(),


ceil(), floor(), log(), sqrt(), etc.
} elseif (condition) {
Example:
// statements;
php
} else {

50
Copy code $name[] = value; # Append value

$a = 3; Example:

$b = 4; php

$c = sqrt(pow($a, 2) + pow($b, 2)); // Copy code


c=5
$a = array(); # Empty array (length 0)
Int and Float Types
$a[0] = 23; # Stores 23 at index 0
Example of type conversion: (length 1)

php $a2 = array("some", "strings", "in",


"an", "array");
Copy code
$a2[] = "Ooh!"; # Add string to end
$a = 7 / 2; // float: 3.5
(at index 5)
$b = (int) $a; // int: 3
Array Functions
$c = round($a); // float: 4.0
Function Description

count Number of elements in the array

print_r Print array's contents


PHP Arrays - Functions
array_pop, array_push, array_shift,
array_unshift Using array as a
stack/queue
3.3 Basic PHP Syntax
in_array, array_search, array_reverse,
Arrays sort, rsort, shuffle Searching and
Creating Arrays: reordering

$name = array(); # Create an empty array_fill, array_merge,


array array_intersect, array_diff,
array_slice, range Creating, filling,
$name = array(value0, value1, ..., filtering
valueN); # Create an array with values
array_sum, array_product,
$name[index] # Get element value array_unique, array_filter,
$name[index] = value; # Set element array_reduce Processing elements
value Array Function Example

51
Arrays in PHP replace many other php
collections in Java (list, stack, queue,
Copy code
set, map).
$fellowship = array("Frodo", "Sam",
php
"Gandalf", "Strider", "Gimli",
Copy code "Legolas", "Boromir");

$tas = array("MD", "BH", "KK", print "The fellowship of the ring


"HM", "JP"); members are: \n";

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

$tas[$i] = strtolower($tas[$i]); foreach ($fellowship as $fellow) {

} print "$fellow\n";

$morgan = array_shift($tas); }

array_pop($tas); Multidimensional Arrays

array_push($tas, "ms"); Example:

array_reverse($tas); php

sort($tas); Copy code

$best = array_slice($tas, 1, 2); $AmazonProducts = array(

Foreach Loop array("Code" => "BOOK",


"Description" => "Books", "Price" =>
Syntax:
50),

array("Code" => "DVDs",


php "Description" => "Movies", "Price"
=> 15),
Copy code
array("Code" => "CDs",
foreach ($array as $variableName) { "Description" => "Music", "Price" =>
... 20)

} );

Example:
for ($row = 0; $row < 3; $row++) {

52
echo "<p> | " . print strpos($test, "o", 5); // Output:
$AmazonProducts[$row]["Code"] . " | position of "o" after index 5
".
Regular Expressions

Patterns in Text:
$AmazonProducts[$row]["Description
"] . " | " . PHP supports POSIX and Perl regular
expressions.
$AmazonProducts[$row]["Price"]
. " </p>"; Examples:
} regex
String Comparison Functions Copy code
Common Functions: [a-z]at # Matches: cat, rat, bat…
strcmp: Compare strings [aeiou] # Matches vowels
strstr, strchr: Find string/char within a [a-zA-Z] # Matches all letters
string
[^a-z] # Not a-z
strpos: Find numerical position of
string [[:alnum:]]+ # At least one
alphanumeric character
str_replace, substr_replace: Replace
strings (very)*large # Matches: large, very
large, very very large…
Example:
(very){1,3} # Counting "very" up to 3
php
^bob # Matches "bob" at the
Copy code beginning
$offensive = array("offensive word1", com$ # Matches "com" at the end
"offensive word2");
Printing HTML Tags in PHP
$feedback = str_replace($offensive,
"%!@*", $feedback); Best practice is to minimize print/echo
statements.

Without print, how to insert dynamic


$test = "Hello World! \n"; content?
print strpos($test, "o"); // Output: Example:
position of first "o"

53
php Unclosed Braces: Results in an error
about 'unexpected $end'.
Copy code
Missing '=' Sign: In <?=, the
print "<!DOCTYPE html PUBLIC \"-
expression does not produce any
//W3C//DTD XHTML 1.1//EN\"\n";
output.
print "
Example:
\"http://www.w3.org/TR/xhtml11/DTD/
xhtml11.dtd\">\n"; php

print "<html Copy code


xmlns=\"http://www.w3.org/1999/xhtml
<body>
\">\n";
<p>Watch how high I can count:
print "<head>\n";
<?php
print "<title>Geneva's web
page</title>\n"; for ($i = 1; $i <= 10; $i++) {
... ?>
for ($i = 1; $i <= 10; $i++) { <?= $i ?>
print "<p> I can count to $i! </p>
</p>\n";
</body>
}
Complex Expression Blocks
PHP Expression Blocks
Example:
Short syntax for embedding PHP
expressions into HTML. php

Syntax: <?= expression ?> Copy code

Example: <body>

php <?php

Copy code for ($i = 1; $i <= 3; $i++) {

<h2> The answer is <?= 6 * 7 ?> ?>


</h2> <h<?= $i ?>>This is a level <?= $i
Common Errors ?> heading.</h<?= $i ?>>

54
<?php for ($i = 1; $i < strlen($str);
$i++) {
}
print $separator . $str[$i];
?>
}
</body>
}
Functions
}
Parameter types and return types are
not explicitly defined.

A function with no return statements print_separated("hello"); # Output:


implicitly returns NULL. h, e, l, l, o

Example: print_separated("hello", "-"); #


Output: h-e-l-l-o
php

Copy code

function quadratic($a, $b, $c) {

return -$b + sqrt($b * $b - 4 * $a *


$c) / (2 * $a);

Default Parameter Values

If no value is passed, the default will be


used.

Example:

php

Copy code

function print_separated($str,
$separator = ", ") {

if (strlen($str) > 0) {

print $str[0];

55

You might also like