CHAPTER 5 to 7
CHAPTER 5 to 7
CHAPTER 5 to 7
CHAPTER 5
STRINGS
1
Strings
$myString = ‘hello’; [OR] $myString = “hello”;
For example:
<?php Output:
Hello World!
$myString = ‘world’; Hello, $myString!
echo “Hello” . “<br>”;
echo "Hello, $myString! <br/>";
echo 'Hello, $myString! <br/>';
?>
2
Common escape sequences
Sequence Meaning
\\ A backslash
\$ A $ symbol
\” A double quote
Output: Syntax:
There is a “big dog” at the background. echo "There is a \"big
dog\" at the background.";
3
Working with Character Strings
characters : letters, numbers, and punctuation
a character string : a series of characters.
When a number is used as a character,
it is just a stored character, the same as a letter. (09 434456787)
can’t be used in arithmetic. (Not- 3+5)
When a character string store in a variable, double quotes or single quotes are used.
4
Working with Character Strings
<?php
$number = 10;
$string1 ="There are '$number' people in line.";
Output:
$string2 ='There are "$number" people waiting.'; There are ‘10’ people in line.
echo $string1."<br/>"; There are “$number” people waiting.
echo $string2;
?>
5
Accessing Characters within a String
$myString = “Hello, world!”;
$myString[12] = ‘?’;
echo $myString . “ <br /> ”; // Displays ‘Hello, world?’
6
Manipulating strings
PHP provides many built-in functions for manipulating strings.
trim() removes white space from the beginning and end of a string
ltrim() removes white space only from the beginning of a string
rtrim() removes white space only from the end of a string
For example:
<?php Output:
$myString = " What a lot of space! "; |What a lot of space!|
echo "|".trim($myString)."|<br/>"; |What a lot of space! |
echo "|".ltrim($myString)."|<br/>"; | What a lot of space!|
echo "|".rtrim($myString)."|<br/>";
?>
7
str_repeat() and str_replace()
(1) str_repeat() function (2) str_replace () function
8
strchr() and stristr()
(3) strchr() function (4) stristr() function
9
strlen() and strpos()
(5) strlen() function (6) strpos() function
10
strrchr() and strrev()
(7) strrchr() function (8) strrev() function
11
strrpos() and strtolower()
(9) strrpos() function (10) strtolower() function
12
strtoupper() and strtr()
(11) strtoupper() function (12) strtr() function
Function format : strtr(“string”, “str1”, “str2”)
Function format : strtoupper(“string”) Example:
Example: <?php
<?php $str= “aa bb cc”;
$str = strtoupper(“yes”); $new=strtr($str, “bb” , “xx”);
echo $str; echo $new;
?> // $str=YES ?> // $new=aa xx cc
13
substr() and substr_count()
(13) substr() function (14) substr_count() function
14
substr_replace() and strpbrk()
(15) substr_replace() function (16) strpbrk() function
15
ucfirst() and ucwords()
(17) ucfirst() function (18) ucwords() function
16
Formatting output strings
The output produced by PHP is always in string format.
<?php
$number = 4; Eg
echo “Sally has $number children.”; <?php
?> //The output is : Sally has 4 children. printf("%d times %d is %d.<br>",2,3,2*3);
?>
17
Padding the Output
Padding Strings with str_ pad()
<?php Output:
echo str_pad("Hello, world!",20)."<br>"; Hello, world!
echo str_pad("Hello, world!",20,"*")."<br/>"; Hello, world!*******
echo str_pad("Hello, world!",20,"123")."<br/>"; Hello, world!1231231
?>
18
Working with Dates and Times
Dates and times can be important elements in a script.
The computer stores dates and times in a format called a timestamp, which is expressed entirely
in seconds.
PHP converts dates from your notation into a timestamp the computer understands and from a
timestamp into a format that is familiar to people.
Formatting dates
$mydate = date(“format”,$timestamp);
The timestamp format is a UNIX Timestamp, an integer that is the number of seconds from
January 1, 1970 00:00:00 GMT(Greenwich Mean Time) to the time represented by the
timestamp.
19
Working with Dates and Times
Example:
$today = date(“Y/m/d”);
If today is April 26, 2018, this statement returns: 2018/04/26
$todayMO = date("m");
$todayDay= date("d");
$startYr = date("Y");
20
Working with Dates and Times
21
Working with Dates and Times
Storing a timestamp in a variable
$today = time(); // timestamp with the current date and time
$today = strtotime(“today”); //today’s timestamp
Example:
$importantDate = mktime(0,0,0,1,15,2003);
22
Working with Dates and Times
strtotime recognizes the words and abbreviations in a variety of ways.
Example:
23
Working with Dates and Times
<!DOCTYPE html> echo date("Y-m-d h:i:sa", $d) . "<br>";
<html>
$d=strtotime("tomorrow"); ?>
</body>
24
University of Computer Studies, Pyay
CHAPTER 6
ARRAYS
25
Outlines
Building arrays
Assigning values to arrays
Sorting arrays
Using values in arrays
Building multidimensional arrays
26
Arrays
Arrays are complex variables that store a group of values under a single variable name.
An array is useful for storing a group of related values.
Information in an array can be handled, accessed, and modified easily.
27
Creating Arrays
1. Numeric array
<?php>
0 1 2
$names[0] = "Mg Mg"; name Mg Mg Ma Ma Mi Mi
$names[1] = "Ma Ma"; s
$names[2] = "Mi Mi";
echo $names[1]." and ".$names[2]." are ".$names[0]." 's neighbours";
?>
<?php>
$names =array(“Mg Mg”,”Ma Ma”,”Mi Mi”);
?> Output:
Ma Ma and Mi Mi are Mg Mg’s neighbours
28
Creating Arrays
2. Associated Array
An associative array is indexed with strings between the square brackets rather than numbers.
Whereas numerical arrays are indexed numerically, associative arrays are indexed using
names.
An array can be viewed as a list of key/value pairs, stored as follows:
$arrayname[‘key1’] = value1;
$arrayname[‘key2’] = value2;
$arrayname[‘key3’] = value3;
The key is also referred to as the index.
This associative array is useful in Database.
29
Creating Arrays <?php>
$myBook[“title”] = “TheGrapes of Warth";
For example, $myBook[“author”] = “John Steinbeck";
$myBook[“pubYear”] = 1939;
$myBook = array( “title” => “The Grapes of Wrath”,
?>
“author” => “John Steinbeck”,
“pubYear” => 1939);
echo "Title is ".$myBook["title"]."<br>"."Author is ".
$myBook["author"]."<br>"."Publish Year is ".$myBook["pubYear"];
30
Creating Arrays
Create an array with a range of values by using the Output(Example1):
following statement: $years[0] = 2001
$years[1] = 2002
Example1:
...
$years = range(2001, 2010); $years[8] = 2009
$years[9] = 2010
print_r ($years);
Output(Example2):
$reverse_letters[0]=z
Example2: $reverse_letters[1]=y
...
$reverse_letters= range(“z”, “a”); $reverse_letters[24]=b
print_r ($reverse_letters); $reverse_letters[25]=a
31
Example
<?php
$address['name'] = "Peter"; Output:
$address['occupation'] = "actor"; Peter is 30 years old.
$address['age'] = "30"; name: Peter
echo $address["name"] . " is " . $address["age"] . " years old.<br>"; occupation: actor
foreach($address as $key=>$value) age: 30
{
echo "<b>$key:</b> $value<br/>";
}
?>
32
Example
<html>
Output:
<body>
Peter is 35 years old.
<?php
$age=array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
</body>
</html>
33
Example
<html> Output:
Key=Peter, Value=35
<body>
Key=Ben, Value=37
<?php Key=Joe, Value=43
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $k => $value){
echo "Key=" . $k . ", Value=" . $value;
echo "<br/>";
}
?>
</body>
</html>
34
Outputting an Entire Array with print_r()
Can see the structure and values of any array by using one of two statements : var_dump or
print_r.
To display the $customers array: print_r($customers);
This print_r statement provides the following output:
Array ( [1] => Sam [2] => Sue [3] => Mary )
This above output shows the key and the value for each element in the array.
35
Outputting an Entire Array with var_dump()
To get more information, use the following statement:
var_dump($customers); array(3) {
[1]=>string(3) “Sam”
[2]=>string(3) “Sue”
[3]=>string(4) “Mary”
}
36
Working with Multidimensional Arrays
Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array.
And each element in the sub-array can be an array, and so on.
Griffin
<?php Peter Lois Megan
$families = array (
array("Peter","Lois","Megan"), Quagmire
array("Glenn"), Glenn
array("Cleveland","Loretta","Junior") Brown
); CleveLa Loretta Junior
echo $families[0][0]; //Output-Peter nd
?>
37
Working with Multidimensional Arrays
Multidimensional Arrays
Griffin
Peter Lois Megan
<?php
$families = array("Griffin" => array("Peter","Lois","Megan"), Quagmire
"Quagmire" => array("Glenn"), Glenn
"Brown" => array("Cleveland","Loretta","Junior")
); Brown
echo $families['Griffin'][0]; //Output-Peter CleveLa Loretta Junior
nd
?>
38
Modifying Arrays
array_push($arraya, $d);
<?php Output:
$arraya = array(“a”,”b”,”c”); Array ( [0] => a [1] => b [2] => c )
print_r($arraya);
echo("<br>") ; Array ( [0] => a [1] => b [2] => c [3] => d )
foreach($arraya as $key=>$value)
{ if($value == 'b')
{ $d = 'd';
array_push($arraya, $d); //value d is inserted in arraya
print_r($arraya);
}
}
?>
39
Removing values from arrays
unset($my_array[1]);
Output:
Example1:
Element 1
<?php Element 2
$my_array = array("Element 1", "Element 2", "Element 3"); Element 3
foreach ($my_array as $name)
{
echo "$name<br>";
}
unset($my_array[0]);
foreach ($my_array as $name)
{ Output:
echo "$name<br>"; Element 2
} Element 3
?>
40
Removing values from arrays
Example2:
<?php Output:
$colors = array ( "red", "green", "blue", "pink", "yellow"); red
$colors[2] = ""; green
foreach($colors as $res) pink
echo($res ."<br>"); yellow
unset($colors[3]);
Output
foreach($colors as $res) red
echo($res ."<br>"); green
?>
yellow
41
PHP Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order, descending or
ascending.
PHP - Sort functions for arrays
42
Sorting Arrays
Sort Array in Ascending Order - sort( )
The following example sorts the elements of the $fruits array in ascending alphabetical order:
Syntax: sort($arraryName);
Example1: Output:
<?php apple
$fruits = array("lemon", "orange", "banana", "apple"); banana
sort($fruits); lemon
foreach ($fruits as $key => $val) orange
{
echo $val."<br/>";
}
?>
43
Sorting Arrays
Example2:
Output:
<?php Austin
$capitals['CA'] = "Sacramento"; Sacramento
Salem
$capitals['TX'] = "Austin";
$capitals['OR'] = "Salem";
asort($capitals) ;
foreach($capitals as $ans=>$value)
echo $value."<br/>";
?>
44
Output:
Volvo
Sorting Arrays Toyota
BMW
Example3:
<html><body>
<?php
$cars=array("BMW","Volvo","Toyota");
rsort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br/>";
}
?>
</body></html> (or)
45
Adding and Removing Array Elements
array_unshift() -Adds one or more new elements to the start of an array
array_shift() -Removes the first element from the start of an array
array_push() -Adds one or more new elements to the end of an array
array_pop() -Removes the last element from the end of an array
array_splice() -Removes element(s) from and/or adds element(s) to any point in an array
can’t add key/value pairs to associative arrays using array_unshift() (or its counterpart,
array_pop() ).
can work around this by using array_merge() .
46
array_shift()
<html>
<body>
<?php
$myBook = array("title" => "The Grapes of Wrath",
"author" => "John Steinbeck",
"pubYear" => 1939);
echo array_shift( $myBook )."<br/>";
print_r( $myBook );
?> Output:
</body> The Grapes of Wrath
</html> Array ( [author] => John Steinbeck [pubYear] => 1939 )
47
array_push()
<html>
<body>
<?php
$authors = array("Steinbeck","Kafka","Tolkien","Dickens");
echo array_push($authors,"Hardy","Melville")."<br/>";
print_r($authors);
?> Output:
6
</body>
Array ( [0] => Steinbeck [1] => Kafka [2] => Tolkien [3] =>
</html> Dickens [4] => Hardy [5] => Melville )
48
Turning the original array into a
multidimensional array using array_push()
Output:
Example: 5
<html>
Array
<body> (
<?php [0] => Steinbeck
$authors = array("Steinbeck","Kafka","Tolkien","Dickens"); [1] => Kafka
$newAuthors = array("Hardy","Melville"); [2] => Tolkien
echo array_push( $authors, $newAuthors )."<br/>"; [3] => Dickens
[4] => Array
echo "<pre>"; (
[0] => Hardy
print_r($authors);
[1] => Melville
echo "</pre>"; )
?> )
</body>
</html>
49
array_pop()
<html>
<body>
<?php
$myBook = array("title" => "The Grapes of Wrath",
"author" => "John Steinbeck",
"pubYear" => 1939);
echo array_pop($myBook). "<br/>";
print_r($myBook);
?> Output:
</body> 1939
</html> Array ( [title] => The Grapes of Wrath [author] => John Steinbeck )
50
array_splice()
print_r( array_splice( $authors, 2, 0, $arrayToAdd ) );
- “At the third position (2), remove zero (0) elements, then insert $arrayToAdd”.
$moreAuthors = "Steven";
array_splice($authors, 0, 2,$moreAuthors);
print_r($authors);
echo "<br>"; Output:
Array ( [0] => Steinbeck [1] => Kafka [2] => Milton [3] => John [4] => Peter )
array_splice($authors, 1); Array ( [0] => Steven [1] => Milton [2] => John [3] => Peter )
print_r($authors); Array ( [0] => Steven )
?>
</body>
</html> 52
Merging Arrays Together
array_merge() joins the array elements of the arrays together to produce the final array.
This contrasts with array_push(), array_unshift(), and the square bracket syntax, which all
insert array arguments as - is to produce multidimensional arrays.
<html> Output:
<body> Array ( [0] => Steinbeck [1] => Kafka [2] => Tolkien [3] => Milton )
<?php
$authors = array("Steinbeck","Kafka");
$moreAuthors = array("Tolkien","Milton");
print_r(array_merge($authors,$moreAuthors));
?>
</body>
</html>
53
Converting Between Arrays and Strings
Converting String to Array: explode()
Example 1:
<html>
<body>
<?php
$fruitString= "apple,pear,banana,strawberry,peach";
$fruitArray = explode(",", $fruitString);
print_r($fruitArray);
?>
</body>
</html>
Output:
Array ( [0] => apple [1] => pear [2] => banana [3] => strawberry [4] =>
peach ) 54
Converting Between Arrays and Strings
Example 2:
<html>
<body>
<?php
$fruitString ="apple,pear,banana,strawberry,peach";
$fruitArray = explode(",",$fruitString,3);
print_r($fruitArray);
?>
</body>
</html>
Output:
Array ( [0] => apple [1] => pear [2] => banana,strawberry,peach )
55
Converting Between Arrays and Strings
Converting Array to String: implode()
Example:
Output:
apple,pear,banana,strawberry,peach
<html>
<body>
<?php
$fruitArray = array("apple","pear","banana","strawberry","peach");
$fruitString = implode(",", $fruitArray );
echo $fruitString;
?>
</body>
</html>
56
Converting an Array to a List of Variables
$myBook = array( “The Grapes of Wrath”, “John Steinbeck”, 1939 );
57
University of Computer Studies, Pyay
CHAPTER 7
FUNCTIONS
58
Outlines
Calling Functions
PHP Function
Understanding Variable Scope (Example)
Working with Global Variables(Example)
Working without References(Example)
Passing References to Your Own Functions(Example)
59
Calling Functions
PHP’s built-in Functions
<?php Output:
The square root of 9 is: 3
echo "The square root of 9 is: ".sqrt(9)."<br/>";
?>
Example
<?php
Output:
$trigFunctions = array("sin","cos","tan"); sin(30) =0.5
cos(30) =0.866025403784
$degrees = 30; tan(30) =0.57735026919
foreach($trigFunctions as $trigFunction)
{
echo "$trigFunction($degrees) =".$trigFunction(deg2rad($degrees))."<br/>";
}
?>
61
PHP Function
Function with no Parameter Function with Parameter
function function_name() function function_name($num)
{ {
block of statements block of statements
function_name(); function_name(5);
} }
Function with no Parameter (Eg)
<?php Function with Parameter
<?php
function myMessage() { function familyName($fname) {
echo "Hello world!"; echo "$fname<br>";
}
} familyName("Jani");
myMessage(); ?>
?> 62
PHP Function
Function with return
function function_name()
{
block of statements
return value;
}
Function Call:
$return_value=function_name()
63
Function with Default Parameters(Eg)
function doIt($num=5)
{
PHP Function echo $num;
}
Function with Default Parameters
doIt();
function function_name($num=5”)
{ Function with Default Parameters(Eg)
block of statements function doIt($num=5)
} {
echo $num;
Function Call: }
function_name() doIt();
64
Understanding Variable Scope (Example)
<?php
$name=“Ma Ma”; Global Variable(Outside the
function)
function helloWithVariables(){
$hello = "Hello, ";
Local Variable(Inside the
$world = "world!"; function)
66
Working with Global Variables(Example)
<?php
$var=20;
function funA(){
global $var;
echo $var;
}
funA();
?>
67
Working with Global Variables(Example)
<?php Output:
function setup() { Hello there!
global $myGlobal;
$myGlobal = "Hello there!";
}
function hello() {
global $myGlobal;
echo "$myGlobal <br/>";
}
setup();
hello();
?>
68
Working without References(Example)
<?php
function resetCounter( $c ) { Output:
$c = 0; 3
} 3
$counter = 0; resetCounter
$counter++; 001
$counter++; $c
$counter++; $counter 3
0
3
echo "$counter<br/>";
resetCounter($counter); 002
echo "$counter<br/>";
?>
69
Passing References(Example)
<?php Output:
function resetCounter(& $c){ 3
$c = 0; 0
resetCounter
}
001
$counter = 0; & $c
$counter++; $counter 0
3
$counter++; 001
$counter++;
3
0
echo "$counter<br/>";
resetCounter( $counter );
echo "$counter<br/>";
?>
70
Different between Pass by Value
and Pass by Reference
71
Thank You
72