Web Dev Final Book Page Num-31-55
Web Dev Final Book Page Num-31-55
$preserve_keys =
• —Remove a portion of the array and
false ]] ) replace
[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
32
• bool arsort ( array &$array [, int • This function sorts an array such that
$sort_flags = array
• <?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) {
} }
?> ?>
• The above example will output: • The above example will output:
asort count
33
COUNT_NORMAL ] ) $varname [, mixed
$a[1] = 3; • <?php
• 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
36
?>
html
Copy code
echo "Hello";
A Function That Does Not Return a
Value }
</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>
return value;
} Example:
Example:
html
<html> <body>
<body> <?php
function sum() {
$s = 10 + 20; }
} printName("Khorn Channa");
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
<?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.
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 />";
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" /> }
</form> <html>
</body> <body>
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);
</head> }
<body> ?>
<?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>
42
</tr> </tr>
<tr> </table>
<td><input type="text"
name="website"></td>
<?php
</tr>
echo "<h2>Your Given Details
<tr> Are:</h2>";
</td> </html>
</tr>
<tr>
<td>
43
PHP provides a wide range of built-in echo $newText; // Outputs: 'I love
string functions. coding'
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
45
Description: Splits a string into an $text = ' Hello World ';
array by a delimiter.
echo trim($text); // Outputs: 'Hello
Example: World'
46
php Definition
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.
48
Comments Object Data Type
49
$length = strlen($name); // 15 // statements;
Control Structures do {
50
Copy code $name[] = value; # Append value
$a = 3; Example:
$b = 4; php
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");
} print "$fellow\n";
$morgan = array_shift($tas); }
array_reverse($tas); php
} );
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.
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
Example: <body>
php <?php
54
<?php for ($i = 1; $i < strlen($str);
$i++) {
}
print $separator . $str[$i];
?>
}
</body>
}
Functions
}
Parameter types and return types are
not explicitly defined.
Copy code
Example:
php
Copy code
function print_separated($str,
$separator = ", ") {
if (strlen($str) > 0) {
print $str[0];
55