SlideShare a Scribd company logo
UNIT II
String Handling and Arrays
Contents
Strings in PHP – String Functions – PHP Arrays – Creating Arrays –
Retrieving Arrays – Multidimensional Arrays – Inspecting Arrays –
Deleting Arrays – Iteration – Numerical Types – Mathematical
Operators – Simple Mathematical Functions – Randomness
Strings in PHP
● Strings are sequences of characters that can be treated as a
unit — assigned to variables, given as input to functions,
returned from functions, or sent as output to appear on your
user’s web page
● The simplest way to specify a string in PHP code is to enclose
it in quotation marks, whether single quotation marks (‘) or
double quotation marks (“), like this:
○ $my_string = ‘A literal string’;
○ $another_string = “Another string”;
Interpolation with curly braces
● When variable interpolation with curly braces is done actually tells the parser
about the start and end of the variable
● Php will evaluate a variable starting with a { and ending with a } and
interpolate the rest of the string as it is
● Example:
<?php
$sports= "cricket";
echo "I will play {$sports}in the summer time";
?>
String operators
● PHP offers two string operators: the dot (.) or concatenation operator and the .=
concatenating assignment operator.
Concatenation operator
● The concatenation operator, when placed between two string arguments, produces a new string
that is the result of putting the two strings together in sequence.
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
Output: Hello world!
Concatenation assignment
● PHP has a shorthand operator (.=) that combines concatenation with assignment.
● Appends $txt2 to $txt1
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2; //($txt1 = $txt1.$txt2;)
echo $txt1;
?>
Output: Hello world!
Heredoc
● PHP offers another way to specify a string, called the heredoc syntax
● Heredoc PHP syntax is a way to write large block of text inside PHP, without the classic single
quote, double quotes delimiters.
● The operator in the heredoc syntax is <<<.
<?php
echo <<<mystring
Everything in this rather unnecessarily wordy
ramble of prose will be incorporated into the
string that we are building up inevitably, inexorably,
character by character, line by line, until we reach that
blessed final line which is this one.
mystring;
?>
Output:
Everything in this rather
unnecessarily wordy ramble of
prose will be incorporated into
the string that we are building up
inevitably, inexorably, character
by character, line by line, until we
reach that blessed final line
which is this one.
String Functions
● The PHP string functions are part of the PHP core.
1.Inspecting strings
● First on the list is how long the string is, using the strlen() function
● strlen() function returns the length of the string
● Example
<?php
$s="hello world";
echo strlen($s);
?>
Output: 11
String Functions
2.Finding characters and substrings
● The strpos() function finds the numerical position of a particular character in a string, if it
exists.
● Example
<?php
$s="hello world";
echo strpos($s,'w');
?>
Output: 6
String Functions
● The strrpos() function finds the position of the last occurrence of a string inside another string.
Related functions:
● strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)
● stripos() - Finds the position of the first occurrence of a string inside another string (case-
insensitive)
● strripos() - Finds the position of the last occurrence of a string inside another string (case-
insensitive)
● Example
<?php
$s="hello world";
echo strrpos($s,'l');
?>
Output: 9
String Functions
3.Comparison and searching
Comparing
The strncmp() function compares two strings.
Note: The strncmp() is binary-safe and case-sensitive.
This function is similar to the strcmp() function, except that strcmp() does not have the length
parameter.
Example:
<?php
$s1="hello";
$s2="Hello";
if (strncmp($s1,$s2,5)==0)
echo "the strings are equal";
else
echo "the strings are not equal";
?>
Output: the strings are not equal
String Functions
3.Comparison and searching
Comparing
The strncasecmp() function compares two strings.
Note: The strncasecmp() is binary-safe and case-insensitive.
Tip: This function is similar to the strcasecmp() function, except that strcasecmp() does not have the
length parameter.
Example:
<?php
$s1="hello";
$s2="Hello";
if (strncasecmp($s1,$s2,5)==0)
echo "the strings are equal";
else
echo "the strings are not equal";
?>
Output: the strings are equal
String Functions
Searching
Comparing
● The strstr() function searches for the first occurrence of a string inside another string.
● This function is case-sensitive. For a case-insensitive search, use stristr() function.
● strchr() Identical to strstr().
● stristr() Identical to strstr() except that the comparison is case independent.
Example:
<?php
$s="Hello world!";
echo strstr($s,"world");
?>
Output: world
String Functions
Substring selection
● The substr() function returns a part of a string.
● The substring starts at the indicated position and continues for as many characters as
specified by the length argument or until the end of the string, if there is no length argument.
Example:
<?php
$s="Hello world";
echo substr($s,6);
?>
Output: world
String Functions
String cleanup functions
● The functions chop(), ltrim(), and trim() are really used for cleaning up untidy strings.
● The chop() (rtrim())function removes whitespaces or other predefined characters from the right end
of a string.
● The trim() function removes whitespace and other predefined characters from both sides of a string.
● ltrim() - Removes whitespace or other predefined characters from the left side of a string
Example:
<?php
$str = "Hello World!";
echo $str;
echo chop($str,"World!");
?>
Output: Hello World!Hello
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
Hello World!
llo Worl
<?php
$str = "Hello World!";
echo $str . "<br>";
echo ltrim($str,"Hello");
?>
Hello World!
World!
String Functions
String replacement
● The str_replace() function replaces some characters with some other characters in a string.
● str_replace(find,replace,string,count)
● The substr_replace() function replaces a part of a string with another string.
● substr_replace(string,replacement,start,length)
Example:
<?php
$s="hello world";
echo str_replace("hello", "welcome",$s);
?>
Output: welcome world
<?php
$s="hello";
echo substr_replace($s,"world",1); // 0 will start
replacing at the first character in the string
?>
Output:hworld
String Functions
Case functions
1. strtolower()
The strtolower() function returns an all-lowercase string. It doesn’t matter if the original is all
uppercase or mixed. This fragment:
<?php
$original = “They DON’T KnoW they’re SHOUTING”;
$lower = strtolower($original);
echo $lower;
?>
returns the string “they don’t know they’re shouting”.
2.strtoupper()
The strtoupper() function returns an all-uppercase string, regardless of whether the original was
all lowercase or mixed:
<?php
$original = “make this link stand out”;
echo(“<B>strtoupper($original)</B>”);
?>
String Functions
Case functions
3.ucfirst()
The ucfirst() function capitalizes only the first letter of a string:
<?php
$original = “polish is a word for which pronunciation depends on
capitalization”;
echo(ucfirst($original));
?>
4.ucwords()
The ucwords() function capitalizes the first letter of each word in a string:
<?php
$original = “truth or consequences”;
$capitalized = ucwords($original);
echo “While $original is a parlor game, $capitalized is a town in New
Mexico.”;
?>
PHP Arrays
Array
● An array is a collection of variables indexed and bundled into a single, easily
referenced super variable that offers an easy way to pass multiple values between
lines of code, functions, and even pages.
Creating Arrays
There are three main ways to create an array in a PHP script:
● by assigning a value into one (and thereby implicitly creating it),
● by using the array() construct, and
● by calling a function that happens to return an array as its value.
1.Direct assignment
The simplest way to create an array is to act as though a variable is already an array and assign a
value into it
Example:
$myarray[1]=” This is my car”
2. The array() construct()
array() function is used to create an array
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Output:
Volvo
BMW
Toyota
Specifying indices using array() (Associative Array)
● Associative arrays are arrays that use named keys that you assign to them.
<?php
$fruit = array(10=> "apple", 20=> "orange");
foreach ($fruit as $x => $x_value)
{
echo "key=".$x;
echo "value=".$x_value."<br>";
}
?>
Output:
key=10 value=apple
key=20 value=orange
Functions returning arrays
● The final way to create an array in a script is to call a function that returns an array.
This may be a user defined function, or it may be a built-in function that makes an
array via methods internal to PHP.
<?php
$myarray = range(1,5);
for($i=0;$i<6;$i++)
{
echo $myarray[$i];
}
?>
Output
12345
Retrieving Values
1.Retrieving by index
The most direct way to retrieve a value is to use its index.
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[1];
?>
output
BMW
Retrieving Values
2.list() construct
● The list() function is an inbuilt function in PHP which is used to assign array values to multiple
variables at a time.
● It accepts a list of variables separated by spaces. These variables are assigned values. At
least one variable must be passed to the function.
<?php
$my_array = array("Dog","Cat","Horse");
list($a, ,$c) = $my_array;// list($a,$b ,$c) = $my_array,list($, ,$c) = $my_array
echo "I like $a and $c.";
?>
output
I like Dog and Horse.
Multidimensional Arrays
● A multidimensional array is an array containing one or more arrays.
<?php
$fruits = array (
array("apple",22,18),
array("orange",15,13),
array("banana",5,2),
);
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
echo $fruits[$i][$j]."<br>";
}}
?>
output
apple
22
18
orange
15
13
banana
5
2
Inspecting Arrays
Simple Functions for Inspecting Arrays
1.is_array()
Takes a single argument of any type and returns a true value if the argument is an array, and false otherwise
Example
<?php
$a = "Hello";
echo "a is " . is_array($a) . "<br>";
$b = array("red", "green", "blue");
echo "b is " . is_array($b) . "<br>";
?>
Output:
a is
b is 1
Inspecting Arrays
2.count() and sizeof()
Takes an array as argument and returns the number of nonempty elements in the array.
Example
<?php
$fruits=array("apple","orange","banana");
echo count($cars);
?>
3.in_array()
The in_array() function searches an array for a specific value.
Takes two arguments: an element and an array
Returns true if the element is contained as a value in the array, false otherwise.
<?php
$fruits = array("apple", "orange", "banana");
if(in_array("apple", $fruits))
echo "match found";
else
echo "not found";
?>
Output:
3
Output:
Match found
Inspecting Arrays
4.isset($array[$key])
Takes an array[key] form and returns true if the key portion is a valid key for the array.
<?php
$fruit = array(10=>"apple",20=>"banana");
echo isset($fruit[10]);
?>
output
1
Deleting from Arrays
unset()
This function is used to delete an element from an array
<?php
$fruits = array("apple", "orange", "banana");
unset($fruits[2]);
for($i=0;$i<3;$i++)
{
echo $fruits[$i];
}
?>
output
appleorange
Iteration
● Each array remembers a particular stored key/value pair as being the current one, and
array iteration functions work in part by shifting that current marker through the internal
list of keys and values.
● The linked-list pointer system is an alternative way to inspect and manipulate arrays, which
exists alongside the system that allows key-based lookup and storage
Iteration methods
● foreach
● current() and next()
● reset()
● end() and prev()
● key()
● each()
● array_walk()
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
Foreach
● The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
● For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
Example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
Output:
red
green
blue
yellow
Current() and next()
● The current() function returns the value of the current element in an array
● The next() function moves the internal pointer to, and outputs, the next element in the array.
Example:
<?php
$fruits = array("Apple","Banana","Orange","Grapes");
echo current($fruits) . "<br>";
echo next($fruits);
?>
Output:
Apple
Banana
reset()
● The reset() function moves the internal pointer to the first element of the array.
Example:
<?php
$fruits = array("Apple","Banana","Orange","Grapes");
echo current($fruits) . "<br>";
echo next($fruits). "<br>";
echo reset($fruits);
?>
Output:
Apple
Banana
Apple
end() and prev()
● The end() function moves the internal pointer to, and outputs, the last element in the array.
● The prev() function moves the internal pointer to, and outputs, the previous element in the array.
Example:
<?php
$fruits = array("Apple","Banana","Orange","Grapes");
echo current($fruits) . "<br>";
echo end($fruits). "<br>";
echo prev($fruits);
?>
Output:
Apple
Grapes
Orange
key()
● The key() function returns the element key from the current internal pointer position.
Example:
<?php
$fruits = array("Apple","Banana","Orange","Grapes");
echo "The key from the current position is: " . key($fruits);
?>
Output:
The key from the current position is: 0
each()
● The each() function returns the current element key and value, and moves the internal pointer
forward.
Example:
<?php
$fruits = array(10=>"Apple",20=>"Banana",30=>"Orange",40=>"Grapes");
while($a=each($fruits))
{
$k=$a['key'];
$v=$a['value'];
echo $k. $v."<br>";
}
?>
Output:
10Apple
20Banana
30Orange
40Grapes
array_walk()
● The array_walk() function runs each array element in a user-defined function. The array's
keys and values are parameters in the function.
Example:
<?php
function myfunction($value,$key)
{
echo "The key $key has the value $value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction");
?>
Output:
The key a has the value red
The key b has the value green
The key c has the value blue
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
Numerical Types
● PHP has only two numerical types:
○ integer (also known as long), and
○ double (also known as float), which correspond to the largest numerical types in the C
language.
● PHP does automatic conversion of numerical types, so they can be freely intermixed in
numerical expressions, and the “right thing” will typically happen. PHP also converts strings
to numbers where necessary.
● In situations where you want a value to be interpreted as a particular numerical type, you
can force a typecast by prepending the type in parentheses, such as:
○ (double) $my_var
○ (integer) $my_var
● Or you can use the functions intval() and doubleval(), which convert their arguments to
integers and doubles, respectively.
Mathematical Operators
Arithmetic operators
Incrementing operators
● The increment operator (++) adds one to the variable it is attached to, and the decrement
operator (--) subtracts one from the variable.
● Each one comes in two flavors, postincrement (which is placed immediately after the
affected variable), and preincrement (which comes immediately before).
● Both flavors have the same side effect of changing the variable’s value, but they have
different values as expressions.
● The postincrement operator acts as if it changes the variable’s value after the
expression’s value is returned, whereas the preincrement operator acts as though it makes
the change first and then returns the variable’s new value
Assignment operators
● All five arithmetic operators have corresponding assignment operators (+=, -=, *=, /=, and %=) that
assign to a variable the result of an arithmetic operation on that variable in one fell swoop.
● The statement:
○ $count = $count * 3;
can be shortened to:
■ $count *= 3;
● and the statement:
○ $count = $count + 17;
Becomes:
$count += 17;
Comparison operators
● PHP includes the standard arithmetic comparison operators, which take simple values (numbers or strings) as
arguments and evaluate to either TRUE or FALSE:
● The < (less than) operator is true if its left-hand argument is strictly less than its right-hand argument but
false otherwise.
● The > (greater than) operator is true if its left-hand argument is strictly greater than its right-hand
argument but false otherwise.
● The <= (less than or equal) operator is true if its left-hand argument is less than or equal to its right-hand
argument but false otherwise.
● The >= (greater than or equal) operator is true if its left-hand argument is greater than or equal to its right-
hand argument but false otherwise.
● The == (equal to) operator is true if its arguments are exactly equal but false otherwise.
● The != (not equal) operator is false if its arguments are exactly equal and true otherwise.
● This operator is the same as <>.
● The === operator (identical to) is true if its two arguments are exactly equal and of the same type.
● The !== operator (not identical to) is true if the two arguments are not equal or not of the same type.
Precedence and parentheses
● Operator precedence rules govern the relative stickiness of operators, deciding which
operators in an expression get first claim on the arguments that surround them
● Arithmetic operators have higher precedence (that is, bind more tightly) than comparison
operators.
● Comparison operators have higher precedence than assignment operators.
● The *, /, and % arithmetic operators have the same precedence.
● The + and – arithmetic operators have the same precedence.
● The *, /, and % operators have higher precedence than + and –.
● When arithmetic operators are of the same precedence, associativity is from left to right
(that is, a number will associate with an operator to its left in preference to the operator on
its right).
● Example: 1 + 2 * 3 - 4 - 5 / 4 % 3
■ Answer is 2 (((1 + (2 * 3)) – 4) – ((5 / 4) % 3))
Simple Mathematical Functions
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
Randomness
● PHP’s functions for generating pseudo-random numbers
rand()
● The rand() function generates a random integer.
Example:
<?php
echo(rand() . "<br>");
echo(rand() . "<br>");
echo(rand(10,100));
?>
Output:
512549293
1132363175
79
srand()
● The srand() function seeds the random number generator (rand()).
Example:
<?php
srand(mktime());
echo(rand());
?>
Output:
32857050
getrandmax()
● The getrandmax() function returns the largest possible value that can be returned by rand().
Example:
<?php
echo(getrandmax());
?>
Output:
2147483647
mt_rand()
● The mt_rand() function generates a random integer using the Mersenne Twister algorithm.
Example:
<?php
echo(mt_rand() . "<br>");
echo(mt_rand() . "<br>");
echo(mt_rand(10,100));
?>
Output:
753337239
811653027
45
mt_srand()
● The mt_srand() function seeds the Mersenne Twister random number generator.
Example:
<?php
mt_srand(mktime());
echo(mt_rand());
?>
Output:
1749664286
mt_getrandmax()
● The mt_getrandmax() function returns the largest possible value that can be returned by
mt_rand().
Example:
<?php
echo(mt_getrandmax());
?>
Output:
2147483647
Ad

More Related Content

Similar to String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College (20)

Php string function
Php string function Php string function
Php string function
Ravi Bhadauria
 
php string part 3
php string part 3php string part 3
php string part 3
monikadeshmane
 
lab4_php
lab4_phplab4_php
lab4_php
tutorialsruby
 
lab4_php
lab4_phplab4_php
lab4_php
tutorialsruby
 
9780538745840 ppt ch03
9780538745840 ppt ch039780538745840 ppt ch03
9780538745840 ppt ch03
Terry Yoast
 
Php
PhpPhp
Php
shakubar sathik
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
Ahmed Swilam
 
Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3
Mohd Harris Ahmad Jaal
 
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptxPHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
Php functions
Php functionsPhp functions
Php functions
JIGAR MAKHIJA
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating strings
Nicole Ryan
 
Lesson 2 php data types
Lesson 2   php data typesLesson 2   php data types
Lesson 2 php data types
MLG College of Learning, Inc
 
07-PHP.pptx
07-PHP.pptx07-PHP.pptx
07-PHP.pptx
GiyaShefin
 
overview of php php basics datatypes arrays
overview of php php basics datatypes arraysoverview of php php basics datatypes arrays
overview of php php basics datatypes arrays
yatakonakiran2
 
07-PHP.pptx
07-PHP.pptx07-PHP.pptx
07-PHP.pptx
ShishirKantSingh1
 
PHP string-part 1
PHP string-part 1PHP string-part 1
PHP string-part 1
monikadeshmane
 
Presentaion
PresentaionPresentaion
Presentaion
CBRIARCSC
 
07 php
07 php07 php
07 php
CBRIARCSC
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
richambra
 
Array String - Web Programming
Array String - Web ProgrammingArray String - Web Programming
Array String - Web Programming
Amirul Azhar
 

More from Dhivyaa C.R (19)

Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Dhivyaa C.R
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeBasics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Learning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering College
Learning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering CollegeLearning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering College
Learning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...
Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...
Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...
Dhivyaa C.R
 
Artificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering College
Artificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering CollegeArtificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering College
Artificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Bayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering College
Bayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering CollegeBayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering College
Bayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Machine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering College
Machine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering CollegeMachine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering College
Machine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Unit v -Construction and Evaluation
Unit v -Construction and EvaluationUnit v -Construction and Evaluation
Unit v -Construction and Evaluation
Dhivyaa C.R
 
Unit iv -Documenting and Implementation of Software Architecture
Unit iv -Documenting and Implementation of Software ArchitectureUnit iv -Documenting and Implementation of Software Architecture
Unit iv -Documenting and Implementation of Software Architecture
Dhivyaa C.R
 
Unit iii-Architecture in the lifecycle
Unit iii-Architecture in the lifecycleUnit iii-Architecture in the lifecycle
Unit iii-Architecture in the lifecycle
Dhivyaa C.R
 
Unit v-Distributed Transaction and Replication
Unit v-Distributed Transaction and ReplicationUnit v-Distributed Transaction and Replication
Unit v-Distributed Transaction and Replication
Dhivyaa C.R
 
Unit iv -Transactions
Unit iv -TransactionsUnit iv -Transactions
Unit iv -Transactions
Dhivyaa C.R
 
Unit iii-Synchronization
Unit iii-SynchronizationUnit iii-Synchronization
Unit iii-Synchronization
Dhivyaa C.R
 
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
Dhivyaa C.R
 
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
Dhivyaa C.R
 
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Dhivyaa C.R
 
Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...
Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...
Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...
Dhivyaa C.R
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Dhivyaa C.R
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeBasics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Learning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering College
Learning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering CollegeLearning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering College
Learning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...
Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...
Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...
Dhivyaa C.R
 
Artificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering College
Artificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering CollegeArtificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering College
Artificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Bayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering College
Bayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering CollegeBayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering College
Bayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Machine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering College
Machine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering CollegeMachine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering College
Machine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Unit v -Construction and Evaluation
Unit v -Construction and EvaluationUnit v -Construction and Evaluation
Unit v -Construction and Evaluation
Dhivyaa C.R
 
Unit iv -Documenting and Implementation of Software Architecture
Unit iv -Documenting and Implementation of Software ArchitectureUnit iv -Documenting and Implementation of Software Architecture
Unit iv -Documenting and Implementation of Software Architecture
Dhivyaa C.R
 
Unit iii-Architecture in the lifecycle
Unit iii-Architecture in the lifecycleUnit iii-Architecture in the lifecycle
Unit iii-Architecture in the lifecycle
Dhivyaa C.R
 
Unit v-Distributed Transaction and Replication
Unit v-Distributed Transaction and ReplicationUnit v-Distributed Transaction and Replication
Unit v-Distributed Transaction and Replication
Dhivyaa C.R
 
Unit iv -Transactions
Unit iv -TransactionsUnit iv -Transactions
Unit iv -Transactions
Dhivyaa C.R
 
Unit iii-Synchronization
Unit iii-SynchronizationUnit iii-Synchronization
Unit iii-Synchronization
Dhivyaa C.R
 
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
Dhivyaa C.R
 
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
Dhivyaa C.R
 
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Dhivyaa C.R
 
Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...
Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...
Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...
Dhivyaa C.R
 
Ad

Recently uploaded (20)

AI Chatbots & Software Development Teams
AI Chatbots & Software Development TeamsAI Chatbots & Software Development Teams
AI Chatbots & Software Development Teams
Joe Krall
 
introduction to Rapid Tooling and Additive Manufacturing Applications
introduction to Rapid Tooling and Additive Manufacturing Applicationsintroduction to Rapid Tooling and Additive Manufacturing Applications
introduction to Rapid Tooling and Additive Manufacturing Applications
vijimech408
 
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdfGROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
kemimafe11
 
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFTDeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
Kyohei Ito
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
David Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And PythonDavid Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And Python
David Boutry
 
Espresso PD Official MP_eng Version.pptx
Espresso PD Official MP_eng Version.pptxEspresso PD Official MP_eng Version.pptx
Espresso PD Official MP_eng Version.pptx
NingChacha1
 
WHITE PAPER-Best Practices in Syngas Plant Optimization.pdf
WHITE PAPER-Best Practices in Syngas Plant Optimization.pdfWHITE PAPER-Best Practices in Syngas Plant Optimization.pdf
WHITE PAPER-Best Practices in Syngas Plant Optimization.pdf
Floyd Burgess
 
Python Functions, Modules and Packages
Python Functions, Modules and PackagesPython Functions, Modules and Packages
Python Functions, Modules and Packages
Dr. A. B. Shinde
 
Health & Safety .........................
Health & Safety .........................Health & Safety .........................
Health & Safety .........................
shadyozq9
 
HSE Induction for heat stress work .pptx
HSE Induction for heat stress work .pptxHSE Induction for heat stress work .pptx
HSE Induction for heat stress work .pptx
agraahmed
 
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation RateModeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Journal of Soft Computing in Civil Engineering
 
UNIT 3 Software Engineering (BCS601) EIOV.pdf
UNIT 3 Software Engineering (BCS601) EIOV.pdfUNIT 3 Software Engineering (BCS601) EIOV.pdf
UNIT 3 Software Engineering (BCS601) EIOV.pdf
sikarwaramit089
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptxUnleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
SanjeetMishra29
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
AI Chatbots & Software Development Teams
AI Chatbots & Software Development TeamsAI Chatbots & Software Development Teams
AI Chatbots & Software Development Teams
Joe Krall
 
introduction to Rapid Tooling and Additive Manufacturing Applications
introduction to Rapid Tooling and Additive Manufacturing Applicationsintroduction to Rapid Tooling and Additive Manufacturing Applications
introduction to Rapid Tooling and Additive Manufacturing Applications
vijimech408
 
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdfGROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
kemimafe11
 
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFTDeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
Kyohei Ito
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
David Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And PythonDavid Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And Python
David Boutry
 
Espresso PD Official MP_eng Version.pptx
Espresso PD Official MP_eng Version.pptxEspresso PD Official MP_eng Version.pptx
Espresso PD Official MP_eng Version.pptx
NingChacha1
 
WHITE PAPER-Best Practices in Syngas Plant Optimization.pdf
WHITE PAPER-Best Practices in Syngas Plant Optimization.pdfWHITE PAPER-Best Practices in Syngas Plant Optimization.pdf
WHITE PAPER-Best Practices in Syngas Plant Optimization.pdf
Floyd Burgess
 
Python Functions, Modules and Packages
Python Functions, Modules and PackagesPython Functions, Modules and Packages
Python Functions, Modules and Packages
Dr. A. B. Shinde
 
Health & Safety .........................
Health & Safety .........................Health & Safety .........................
Health & Safety .........................
shadyozq9
 
HSE Induction for heat stress work .pptx
HSE Induction for heat stress work .pptxHSE Induction for heat stress work .pptx
HSE Induction for heat stress work .pptx
agraahmed
 
UNIT 3 Software Engineering (BCS601) EIOV.pdf
UNIT 3 Software Engineering (BCS601) EIOV.pdfUNIT 3 Software Engineering (BCS601) EIOV.pdf
UNIT 3 Software Engineering (BCS601) EIOV.pdf
sikarwaramit089
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptxUnleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
SanjeetMishra29
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
Ad

String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College

  • 2. Contents Strings in PHP – String Functions – PHP Arrays – Creating Arrays – Retrieving Arrays – Multidimensional Arrays – Inspecting Arrays – Deleting Arrays – Iteration – Numerical Types – Mathematical Operators – Simple Mathematical Functions – Randomness
  • 3. Strings in PHP ● Strings are sequences of characters that can be treated as a unit — assigned to variables, given as input to functions, returned from functions, or sent as output to appear on your user’s web page ● The simplest way to specify a string in PHP code is to enclose it in quotation marks, whether single quotation marks (‘) or double quotation marks (“), like this: ○ $my_string = ‘A literal string’; ○ $another_string = “Another string”;
  • 4. Interpolation with curly braces ● When variable interpolation with curly braces is done actually tells the parser about the start and end of the variable ● Php will evaluate a variable starting with a { and ending with a } and interpolate the rest of the string as it is ● Example: <?php $sports= "cricket"; echo "I will play {$sports}in the summer time"; ?>
  • 5. String operators ● PHP offers two string operators: the dot (.) or concatenation operator and the .= concatenating assignment operator. Concatenation operator ● The concatenation operator, when placed between two string arguments, produces a new string that is the result of putting the two strings together in sequence. <?php $txt1 = "Hello"; $txt2 = " world!"; echo $txt1 . $txt2; ?> Output: Hello world!
  • 6. Concatenation assignment ● PHP has a shorthand operator (.=) that combines concatenation with assignment. ● Appends $txt2 to $txt1 <?php $txt1 = "Hello"; $txt2 = " world!"; $txt1 .= $txt2; //($txt1 = $txt1.$txt2;) echo $txt1; ?> Output: Hello world!
  • 7. Heredoc ● PHP offers another way to specify a string, called the heredoc syntax ● Heredoc PHP syntax is a way to write large block of text inside PHP, without the classic single quote, double quotes delimiters. ● The operator in the heredoc syntax is <<<. <?php echo <<<mystring Everything in this rather unnecessarily wordy ramble of prose will be incorporated into the string that we are building up inevitably, inexorably, character by character, line by line, until we reach that blessed final line which is this one. mystring; ?> Output: Everything in this rather unnecessarily wordy ramble of prose will be incorporated into the string that we are building up inevitably, inexorably, character by character, line by line, until we reach that blessed final line which is this one.
  • 8. String Functions ● The PHP string functions are part of the PHP core. 1.Inspecting strings ● First on the list is how long the string is, using the strlen() function ● strlen() function returns the length of the string ● Example <?php $s="hello world"; echo strlen($s); ?> Output: 11
  • 9. String Functions 2.Finding characters and substrings ● The strpos() function finds the numerical position of a particular character in a string, if it exists. ● Example <?php $s="hello world"; echo strpos($s,'w'); ?> Output: 6
  • 10. String Functions ● The strrpos() function finds the position of the last occurrence of a string inside another string. Related functions: ● strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive) ● stripos() - Finds the position of the first occurrence of a string inside another string (case- insensitive) ● strripos() - Finds the position of the last occurrence of a string inside another string (case- insensitive) ● Example <?php $s="hello world"; echo strrpos($s,'l'); ?> Output: 9
  • 11. String Functions 3.Comparison and searching Comparing The strncmp() function compares two strings. Note: The strncmp() is binary-safe and case-sensitive. This function is similar to the strcmp() function, except that strcmp() does not have the length parameter. Example: <?php $s1="hello"; $s2="Hello"; if (strncmp($s1,$s2,5)==0) echo "the strings are equal"; else echo "the strings are not equal"; ?> Output: the strings are not equal
  • 12. String Functions 3.Comparison and searching Comparing The strncasecmp() function compares two strings. Note: The strncasecmp() is binary-safe and case-insensitive. Tip: This function is similar to the strcasecmp() function, except that strcasecmp() does not have the length parameter. Example: <?php $s1="hello"; $s2="Hello"; if (strncasecmp($s1,$s2,5)==0) echo "the strings are equal"; else echo "the strings are not equal"; ?> Output: the strings are equal
  • 13. String Functions Searching Comparing ● The strstr() function searches for the first occurrence of a string inside another string. ● This function is case-sensitive. For a case-insensitive search, use stristr() function. ● strchr() Identical to strstr(). ● stristr() Identical to strstr() except that the comparison is case independent. Example: <?php $s="Hello world!"; echo strstr($s,"world"); ?> Output: world
  • 14. String Functions Substring selection ● The substr() function returns a part of a string. ● The substring starts at the indicated position and continues for as many characters as specified by the length argument or until the end of the string, if there is no length argument. Example: <?php $s="Hello world"; echo substr($s,6); ?> Output: world
  • 15. String Functions String cleanup functions ● The functions chop(), ltrim(), and trim() are really used for cleaning up untidy strings. ● The chop() (rtrim())function removes whitespaces or other predefined characters from the right end of a string. ● The trim() function removes whitespace and other predefined characters from both sides of a string. ● ltrim() - Removes whitespace or other predefined characters from the left side of a string Example: <?php $str = "Hello World!"; echo $str; echo chop($str,"World!"); ?> Output: Hello World!Hello <?php $str = "Hello World!"; echo $str . "<br>"; echo trim($str,"Hed!"); ?> Hello World! llo Worl <?php $str = "Hello World!"; echo $str . "<br>"; echo ltrim($str,"Hello"); ?> Hello World! World!
  • 16. String Functions String replacement ● The str_replace() function replaces some characters with some other characters in a string. ● str_replace(find,replace,string,count) ● The substr_replace() function replaces a part of a string with another string. ● substr_replace(string,replacement,start,length) Example: <?php $s="hello world"; echo str_replace("hello", "welcome",$s); ?> Output: welcome world <?php $s="hello"; echo substr_replace($s,"world",1); // 0 will start replacing at the first character in the string ?> Output:hworld
  • 17. String Functions Case functions 1. strtolower() The strtolower() function returns an all-lowercase string. It doesn’t matter if the original is all uppercase or mixed. This fragment: <?php $original = “They DON’T KnoW they’re SHOUTING”; $lower = strtolower($original); echo $lower; ?> returns the string “they don’t know they’re shouting”. 2.strtoupper() The strtoupper() function returns an all-uppercase string, regardless of whether the original was all lowercase or mixed: <?php $original = “make this link stand out”; echo(“<B>strtoupper($original)</B>”); ?>
  • 18. String Functions Case functions 3.ucfirst() The ucfirst() function capitalizes only the first letter of a string: <?php $original = “polish is a word for which pronunciation depends on capitalization”; echo(ucfirst($original)); ?> 4.ucwords() The ucwords() function capitalizes the first letter of each word in a string: <?php $original = “truth or consequences”; $capitalized = ucwords($original); echo “While $original is a parlor game, $capitalized is a town in New Mexico.”; ?>
  • 19. PHP Arrays Array ● An array is a collection of variables indexed and bundled into a single, easily referenced super variable that offers an easy way to pass multiple values between lines of code, functions, and even pages. Creating Arrays There are three main ways to create an array in a PHP script: ● by assigning a value into one (and thereby implicitly creating it), ● by using the array() construct, and ● by calling a function that happens to return an array as its value.
  • 20. 1.Direct assignment The simplest way to create an array is to act as though a variable is already an array and assign a value into it Example: $myarray[1]=” This is my car” 2. The array() construct() array() function is used to create an array Example: <?php $cars = array("Volvo", "BMW", "Toyota"); $arrlength = count($cars); for($x = 0; $x < $arrlength; $x++) { echo $cars[$x]; echo "<br>"; } ?> Output: Volvo BMW Toyota
  • 21. Specifying indices using array() (Associative Array) ● Associative arrays are arrays that use named keys that you assign to them. <?php $fruit = array(10=> "apple", 20=> "orange"); foreach ($fruit as $x => $x_value) { echo "key=".$x; echo "value=".$x_value."<br>"; } ?> Output: key=10 value=apple key=20 value=orange
  • 22. Functions returning arrays ● The final way to create an array in a script is to call a function that returns an array. This may be a user defined function, or it may be a built-in function that makes an array via methods internal to PHP. <?php $myarray = range(1,5); for($i=0;$i<6;$i++) { echo $myarray[$i]; } ?> Output 12345
  • 23. Retrieving Values 1.Retrieving by index The most direct way to retrieve a value is to use its index. Example: <?php $cars = array("Volvo", "BMW", "Toyota"); echo $cars[1]; ?> output BMW
  • 24. Retrieving Values 2.list() construct ● The list() function is an inbuilt function in PHP which is used to assign array values to multiple variables at a time. ● It accepts a list of variables separated by spaces. These variables are assigned values. At least one variable must be passed to the function. <?php $my_array = array("Dog","Cat","Horse"); list($a, ,$c) = $my_array;// list($a,$b ,$c) = $my_array,list($, ,$c) = $my_array echo "I like $a and $c."; ?> output I like Dog and Horse.
  • 25. Multidimensional Arrays ● A multidimensional array is an array containing one or more arrays. <?php $fruits = array ( array("apple",22,18), array("orange",15,13), array("banana",5,2), ); for ($i = 0; $i < 3; $i++) { for ($j = 0; $j < 3; $j++) { echo $fruits[$i][$j]."<br>"; }} ?> output apple 22 18 orange 15 13 banana 5 2
  • 26. Inspecting Arrays Simple Functions for Inspecting Arrays 1.is_array() Takes a single argument of any type and returns a true value if the argument is an array, and false otherwise Example <?php $a = "Hello"; echo "a is " . is_array($a) . "<br>"; $b = array("red", "green", "blue"); echo "b is " . is_array($b) . "<br>"; ?> Output: a is b is 1
  • 27. Inspecting Arrays 2.count() and sizeof() Takes an array as argument and returns the number of nonempty elements in the array. Example <?php $fruits=array("apple","orange","banana"); echo count($cars); ?> 3.in_array() The in_array() function searches an array for a specific value. Takes two arguments: an element and an array Returns true if the element is contained as a value in the array, false otherwise. <?php $fruits = array("apple", "orange", "banana"); if(in_array("apple", $fruits)) echo "match found"; else echo "not found"; ?> Output: 3 Output: Match found
  • 28. Inspecting Arrays 4.isset($array[$key]) Takes an array[key] form and returns true if the key portion is a valid key for the array. <?php $fruit = array(10=>"apple",20=>"banana"); echo isset($fruit[10]); ?> output 1
  • 29. Deleting from Arrays unset() This function is used to delete an element from an array <?php $fruits = array("apple", "orange", "banana"); unset($fruits[2]); for($i=0;$i<3;$i++) { echo $fruits[$i]; } ?> output appleorange
  • 30. Iteration ● Each array remembers a particular stored key/value pair as being the current one, and array iteration functions work in part by shifting that current marker through the internal list of keys and values. ● The linked-list pointer system is an alternative way to inspect and manipulate arrays, which exists alongside the system that allows key-based lookup and storage Iteration methods ● foreach ● current() and next() ● reset() ● end() and prev() ● key() ● each() ● array_walk()
  • 32. Foreach ● The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. ● For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element. Example: <?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?> Output: red green blue yellow
  • 33. Current() and next() ● The current() function returns the value of the current element in an array ● The next() function moves the internal pointer to, and outputs, the next element in the array. Example: <?php $fruits = array("Apple","Banana","Orange","Grapes"); echo current($fruits) . "<br>"; echo next($fruits); ?> Output: Apple Banana
  • 34. reset() ● The reset() function moves the internal pointer to the first element of the array. Example: <?php $fruits = array("Apple","Banana","Orange","Grapes"); echo current($fruits) . "<br>"; echo next($fruits). "<br>"; echo reset($fruits); ?> Output: Apple Banana Apple
  • 35. end() and prev() ● The end() function moves the internal pointer to, and outputs, the last element in the array. ● The prev() function moves the internal pointer to, and outputs, the previous element in the array. Example: <?php $fruits = array("Apple","Banana","Orange","Grapes"); echo current($fruits) . "<br>"; echo end($fruits). "<br>"; echo prev($fruits); ?> Output: Apple Grapes Orange
  • 36. key() ● The key() function returns the element key from the current internal pointer position. Example: <?php $fruits = array("Apple","Banana","Orange","Grapes"); echo "The key from the current position is: " . key($fruits); ?> Output: The key from the current position is: 0
  • 37. each() ● The each() function returns the current element key and value, and moves the internal pointer forward. Example: <?php $fruits = array(10=>"Apple",20=>"Banana",30=>"Orange",40=>"Grapes"); while($a=each($fruits)) { $k=$a['key']; $v=$a['value']; echo $k. $v."<br>"; } ?> Output: 10Apple 20Banana 30Orange 40Grapes
  • 38. array_walk() ● The array_walk() function runs each array element in a user-defined function. The array's keys and values are parameters in the function. Example: <?php function myfunction($value,$key) { echo "The key $key has the value $value<br>"; } $a=array("a"=>"red","b"=>"green","c"=>"blue"); array_walk($a,"myfunction"); ?> Output: The key a has the value red The key b has the value green The key c has the value blue
  • 41. Numerical Types ● PHP has only two numerical types: ○ integer (also known as long), and ○ double (also known as float), which correspond to the largest numerical types in the C language. ● PHP does automatic conversion of numerical types, so they can be freely intermixed in numerical expressions, and the “right thing” will typically happen. PHP also converts strings to numbers where necessary. ● In situations where you want a value to be interpreted as a particular numerical type, you can force a typecast by prepending the type in parentheses, such as: ○ (double) $my_var ○ (integer) $my_var ● Or you can use the functions intval() and doubleval(), which convert their arguments to integers and doubles, respectively.
  • 43. Incrementing operators ● The increment operator (++) adds one to the variable it is attached to, and the decrement operator (--) subtracts one from the variable. ● Each one comes in two flavors, postincrement (which is placed immediately after the affected variable), and preincrement (which comes immediately before). ● Both flavors have the same side effect of changing the variable’s value, but they have different values as expressions. ● The postincrement operator acts as if it changes the variable’s value after the expression’s value is returned, whereas the preincrement operator acts as though it makes the change first and then returns the variable’s new value
  • 44. Assignment operators ● All five arithmetic operators have corresponding assignment operators (+=, -=, *=, /=, and %=) that assign to a variable the result of an arithmetic operation on that variable in one fell swoop. ● The statement: ○ $count = $count * 3; can be shortened to: ■ $count *= 3; ● and the statement: ○ $count = $count + 17; Becomes: $count += 17;
  • 45. Comparison operators ● PHP includes the standard arithmetic comparison operators, which take simple values (numbers or strings) as arguments and evaluate to either TRUE or FALSE: ● The < (less than) operator is true if its left-hand argument is strictly less than its right-hand argument but false otherwise. ● The > (greater than) operator is true if its left-hand argument is strictly greater than its right-hand argument but false otherwise. ● The <= (less than or equal) operator is true if its left-hand argument is less than or equal to its right-hand argument but false otherwise. ● The >= (greater than or equal) operator is true if its left-hand argument is greater than or equal to its right- hand argument but false otherwise. ● The == (equal to) operator is true if its arguments are exactly equal but false otherwise. ● The != (not equal) operator is false if its arguments are exactly equal and true otherwise. ● This operator is the same as <>. ● The === operator (identical to) is true if its two arguments are exactly equal and of the same type. ● The !== operator (not identical to) is true if the two arguments are not equal or not of the same type.
  • 46. Precedence and parentheses ● Operator precedence rules govern the relative stickiness of operators, deciding which operators in an expression get first claim on the arguments that surround them ● Arithmetic operators have higher precedence (that is, bind more tightly) than comparison operators. ● Comparison operators have higher precedence than assignment operators. ● The *, /, and % arithmetic operators have the same precedence. ● The + and – arithmetic operators have the same precedence. ● The *, /, and % operators have higher precedence than + and –. ● When arithmetic operators are of the same precedence, associativity is from left to right (that is, a number will associate with an operator to its left in preference to the operator on its right). ● Example: 1 + 2 * 3 - 4 - 5 / 4 % 3 ■ Answer is 2 (((1 + (2 * 3)) – 4) – ((5 / 4) % 3))
  • 49. Randomness ● PHP’s functions for generating pseudo-random numbers
  • 50. rand() ● The rand() function generates a random integer. Example: <?php echo(rand() . "<br>"); echo(rand() . "<br>"); echo(rand(10,100)); ?> Output: 512549293 1132363175 79
  • 51. srand() ● The srand() function seeds the random number generator (rand()). Example: <?php srand(mktime()); echo(rand()); ?> Output: 32857050
  • 52. getrandmax() ● The getrandmax() function returns the largest possible value that can be returned by rand(). Example: <?php echo(getrandmax()); ?> Output: 2147483647
  • 53. mt_rand() ● The mt_rand() function generates a random integer using the Mersenne Twister algorithm. Example: <?php echo(mt_rand() . "<br>"); echo(mt_rand() . "<br>"); echo(mt_rand(10,100)); ?> Output: 753337239 811653027 45
  • 54. mt_srand() ● The mt_srand() function seeds the Mersenne Twister random number generator. Example: <?php mt_srand(mktime()); echo(mt_rand()); ?> Output: 1749664286
  • 55. mt_getrandmax() ● The mt_getrandmax() function returns the largest possible value that can be returned by mt_rand(). Example: <?php echo(mt_getrandmax()); ?> Output: 2147483647
  翻译: