0% found this document useful (0 votes)
32 views92 pages

AIP Chapter 1

Uploaded by

tigisttesfaye301
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)
32 views92 pages

AIP Chapter 1

Uploaded by

tigisttesfaye301
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/ 92

INJIBARA UNIVERSITY

COLLEGE OF ENGINEERING AND TECHNOLOGY


Department of Information Technology

Course Code ITec3093


Course Title Internet Programming II
By: Ayenew K. (MSc.)
Email: [email protected]
Outline
 Overview of Client Side Script
 Introduction to Server Side Script
 What is PHP
 PHP Syntax
 PHP Comments
 PHP Variables
 PHP Data types
 Manipulating strings
 PHP Numbers
 PHP Constants
Chapter : One

Introduction to Server Side Scripting Basics


Overview of web scripting
• Web page -is a single document display on the browser.

• Home page -is a default page that is loaded into a browser when it is opened.

• Web site -is a collection of related web pages. Has a globally unique name.

• HTTP- used to exchange request/response message between web browser and web server.

• Web Browser- an application software that used to view pages available over internet.
Cont.…
 Web server- is a software which provides documents when requested by web browsers via HTTP.

 WWW- A collection of websites stored in web servers.

 URL- The exact address of a resource on the web. It have its own formats. (Protocol, hostname(Domain),

path ).

 DNS-Resolves a human friendly name to a machine friendly name.( www.amazon.com to 198.162.10.1)

 Hypertext -is a way of moving from one web page to another.

 ISP- is a commercial company that sells Internet connections to users. (e.g.: Ethio telecom)

 Internet- network of networks that connects millions of computers across the world.
Cont.…
Scripts- are a series of commands that are able to be executed without the need for compiling.

It can be carried out on client side or server side.

Web scripting- is a process of creating and embedding scripts in a web page.

The content of the web page will not be the same every time you look at it;

It will change dynamically depending on certain factors such as the actions of the person

viewing the page.

Web site can be :


Static Vs Dynamic Web Sites

Static Websites
 Written in HTML and CSS only – web pages
 Pages are separate documents
 No database that draws to it
 In a nutshell:

• Simple web pages with no interactivity


Cont...

Dynamic Websites
 Requires more complex coding
 Web pages can do much more – they are interactive!
 Examples – login page, search pages, querying a backend database
 Uses three major technologies:

• Markup language like HTML


• Scripting languages (both client and server side)
• Stylesheets (for presentation) like CSS
Static Vs Dynamic Web Sites

Static Dynamic

Simple to code (HTML only) Complex coding (HTML + scripting +


style sheet + PHP)

No database connection Usually connects to either flat files or a


database

Quick to develop Takes longer to develop

No user interaction Emphasizes on user interaction (e.g. fill


up a form, login)
8
Client-Side Scripting Vs Server-Side Scripting
Client-side Server-side

Scripts are stored on the client (engine is in Scripts are stored on the server (engine is on
browser) server)

Scripts can be modified by the end user Scripts cannot be modified by the end user

Browser-dependent Browser-independent

Source code can be viewed Source code can’t be viewed

Can’t communicate with a database Can communicate with a database

No network overhead Dependent on network bandwidth

Processing is done by the browser - fast Processing is done by the server - slower

9
What is PHP ?

 PHP is an acronym for "PHP: Hypertext Preprocessor"

 PHP is a widely-used, open source scripting language

 PHP scripts are executed on the server

 PHP is free to download and use

 PHP code is executed on the server, and

 The result is returned to the browser as plain HTML

 PHP files have extension ".php"

10
What is a PHP file?

• PHP files are returned to the browser as plain HTML.

• PHP file scripts are executed on the server.

• PHP files have a file extension of ".php“

• PHP files can contain text, HTML tags and scripts.

• PHP file is Interpreted rather than compiled like Java or C.

11
Cont.…

• An embedded scripting language, meaning that it can exist within HTML code.

• Cross-platform, meaning it can be run on Linux, Windows, Macintosh, etc.,


making PHP very portable.

• Compatible with almost all servers used today (Apache, IIS, etc.)

• Supports many databases (MySQL, Informix, Oracle, Sybase, Solid,


PostgreSQL, Generic ODBC, etc.).

• Easy to learn and runs efficiently on the server side

12
What Can PHP Do?
• PHP can generate dynamic page content

• PHP can create, open, read, write, delete, and close files on the server

• PHP can collect form data

• PHP can send and receive cookies

• PHP can add, delete, modify data in your database

• PHP can be used to control user-access

• PHP can encrypt data

13
PHP Does Not…

• Handle client-side tasks such as creating a new browser window, adding


mouse overs, determining the screen size of the user’s machine, etc. Such
tasks are handled by JavaScript .

• Do anything within the Web browser until a request from the client has been
made (e.g., submitting a form, clicking a link, etc.).

14
Why Use PHP?

• PHP has been described as being “better, faster, and easier to learn than the
alternatives”

• PHP runs on various platforms (Windows, Linux, Unix, Mac OS , etc.)

• PHP is compatible with almost all servers used today (Apache, IIS, etc.)

• PHP supports a wide range of databases (MySQL, Informix, Oracle, Sybase, Solid,
PostgreSQL, Generic ODBC, Microsoft SQL Server etc)

• PHP is free. Download it from the official PHP resource.

15
Cont..

• Allows easy storage and retrieval of information from supported database.

• Accessibility: You can reach the internet from any browser, any device, anytime,
anywhere.

• Manageability: It does not require distribution of application code and it is easy


to change code.

• Security: The source code is not exposed. Once user is authenticated, can only
allow certain actions. It also allows encryption.

• Scalability: Web-based 3-tier architecture can scale out


16
How do I start PHP code?
• Run Your First PHP Script
 Download and Install XAMPP server.

 Open and start Apache and MySQL server .

 Go to XAMPP server directory. I'm using Windows, so my root server directory is


C:\xampp

 Open htdocs\.

 Create folder-IT2017(folder name)

 Install text editor (notepad, notepad++,sublime text…) , open and write code

 save a file as “lab1.php” under “IT2017” folder.


 Finally run the code by writing “localhost/foldername“ on the browser. 17
PHP Basic Syntax
• What is PHP syntax?

• Start your PHP code with <?php and end it with ?>.

• Alternatively, you can use <? and ?>.

• Every PHP line of code ends with a semicolon(;).

• If most of the page content is HTML, the PHP code is usually embedded.

• PHP code typically resides in a plaintext file with a .php extension.

• The code itself is defined within PHP delimiters: <?php and end ?>.

18
PHP Basic Syntax
The PHP parsing engine needs a way to differentiate PHP code from other elements
in the page. The mechanism for doing so is known as ‘escaping to PHP.’ There are four
ways to do this:
1. Canonical PHP tags
The most universally effective PHP tag style is:
If you use this style, you can be positive that your tags will always be correctly interpreted.

2. Short-open (SGML-style) tags: Short tags are, as one might expect, the shortest option.
We must do one of two things to enable PHP to recognize the tags:
19
PHP Basic Syntax
 Choose the --enable-short-tags configuration option when building PHP.
 Set the short_open_tag setting in php.ini file to on. This option must be disabled to parse
XML with PHP because the same syntax is used for XML tags.

3. ASP-style tags: ASP-style tags mimic the tags used by Active Server Pages to delineate
code blocks. To use ASP-style tags, we should set the configuration option in your php.ini
file.

4. HTML script tags: HTML script tags look like this


20
Cont…
• The PHP interpreter considers anything outside of these delimiters as plaintext to
be sent to the client.

• A PHP scripting block can be placed anywhere in the document.

• For maximum compatibility, it is recommended to use the standard form rather


than the shorthand form : 21
PHP Output Statement

• As shown above PHP has different syntaxes but for maximum


compatibility, it is recommended to use <?php…?> .

• Each code line in PHP must end with a semicolon. The semicolon is a
separator and is used to distinguish one set of instructions from another.

• There are two basic statements to output text with PHP:

1. echo

2. print.

22
PHP Output Statement

• echo has no return value whereas print has a return value.

• The returned value represents whether the print statement is succeeded or not.

• If the print statement succeeds, the statement returns 1 otherwise 0.

• echo can take multiple parameters but print can only take one argument.
echo is marginally faster than print.

 The echo or print statement can be used with or without parentheses:

echo or echo().

23
Cont..

• The general format of the echo statement is as follows:


echo outputitem1,outputitem2,outputitem3, . . .;
echo (output statement);
The parameterized version of echo does not accept multiple arguments.

• The general format of the print statement is as follows:


print outputstatement;
print(outputstatement);

24
echo/print
• Example: different ways of echo and print
echo 123; //output: 123
echo “Hello World!”; //output: Hello world!
echo (“Hello World!”); //output: Hello world!
echo “Hello”,”World!”; //output: Hello World!
echo Hello World!; //output: error, string should be enclosed in quotes
print (“Hello world!”); //output: Hello world!

• print (“Hello”, “world!”); //output: _______???

• print “Hello”, “world!”; //output: _______???

• echo (“Hello”, “World!”); //output: _______???


25
PHP Comments
• A comment in PHP code is a line that is not executed as a part of the program.
• Comments can be used to Let others understand your code and Remind yourself of
what you did.
• PHP supports several ways of commenting: single line and multiline.
• Single-line comments: They are generally used for short explanations or notes relevant to
the local code. Here are the examples of single line comments.

26
Cont..

• Multi-lines comments: They are generally used to provide pseudo code


algorithms and more detailed explanations when necessary.
• The multiline style of commenting is the same as in C. Here is the
example of multiline comments.

27
PHP variables
• Variables are "containers" for storing information.
• A variable can hold numbers, doubles, strings, Booleans, objects, arrays,
resources or it can be NULL.

• The syntax for PHP variables is similar to C++ and most other programming
languages Like, Java.

• Variables do not need to be declared before being used.

• Note: PHP is a Loosely Typed Language

28
Cont..

• They are dynamically typed, so you do not need to specify the type .

• Unlike other programming languages, PHP has no command for declaring a


variable (e.g., int, float, etc.).

• It is created the moment you first assign a value to it.

29
PHP Variable Naming Conventions

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable

 A variable name must start with a letter or the underscore character

 A variable name cannot start with a number

 A variable name can only contain alpha-numeric characters and


underscores (A-z, 0-9, and _ )

 Variable names are case-sensitive ($age and $AGE are two different variables)

30
Cont…
 PHP variables can only contain alpha-numeric characters and underscores. a-z, A-Z,
0-9, or _ .

 Variables with more than one word should be separated with underscores:
$my_variable. (not contain space)

 Variables with more than one word can also be distinguished with capitalization:
$myVariable.

 We can uncreated the variable by using this statement: unset(VariableName);

 It is possible to unset more than one variable at once,: unset($age, $name);

31
What you say the following variable name rules?
1. $information technology Invalid (no spaces allowed)

2. $3information Invalid (variable names cannot start with a number)

3. 3$information Invalid (variable names cannot start with a number)

4. $@information Invalid (special characters are not allowed)

5. $information.technology Invalid (periods are not allowed in variable names)

6. $informationTechnology Valid (CamelCase is a good practice)

7. _$information Valid (leading underscores are fine)

8. Information Valid (though variable names are case-sensitive)

9. $information = $Information Valid (treated as different variables)

10. $_information Valid (leading underscores and lowercase are fine)


32
Variable References

• PHP also allows you to do some neat things with variables.

• It allows you to create aliases for variables, and it also allows you to have
variables whose name is a variable.

• A variable reference is a variable assigned to refer to the same information


as another variable.

• To assign an alias to a variable, you use the reference operator, which is an


equals sign followed by an ampersand (= &)

33
Cont.…

34
Predefined / Environment Variables
• Beyond the variables you declare in your code, PHP has a collection of
environment variables, which are system defined variables that are accessible
from anywhere inside the PHP code.

• These variables allow the script access to server information, form parameters,
environment information, etc.

• All of these environment variables are stored by PHP as arrays.

• Some you can address directly by using the name of the index position as a
variable name. Other can only be accessed through their arrays.
35
Cont.…
• $GLOBALS — References all variables available in global scope
• Superglobals — Superglobals are built-in variables that are always available in all scopes
• $_SERVER — Server and execution environment information
• $_GET — HTTP GET variables
• $_POST — HTTP POST variables
• $_FILES — HTTP File Upload variables
• $_REQUEST — HTTP Request variables, and can replace $_POST, $_GET and $_COOKIE
variables
• $_SESSION — Session variables
• $_COOKIE — HTTP Cookies
• $php_errormsg — The previous error message
• $HTTP_RAW_POST_DATA — Raw POST data
• $http_response_header — HTTP response headers
• $argc — The number of arguments passed to script
• $argv — Array of arguments passed to script 36
Display Variables
The following example shows how to output text and variables with
the print statement:
<?php
$txt1 = “Students ";
$txt2 = “Third Year ";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>//output ??? 37
Variables Scope
• In PHP, variables can be declared anywhere in the script.

• The scope of a variable is the part of the script where the variable can be
referenced/used.

• PHP has different variable scopes:

 Local

Global

Static

38
Global Scope
• A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:
• Example
• Variable with global scope:
• <?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?> 39
Local Scope
• A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
• Example
• Variable with local scope:
• <?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>
40
Cont.…
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
• <?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
echo "$y"."<br>";
}
myTest();
echo $y; // outputs what will be the code if the outputs = 15 15 and ??
?> 41
Cont.…
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable. This array is also accessible from within functions and can be used
to update global variables directly.
The example above can be rewritten like this:
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS["y"] = $GLOBALS['x'] + $GLOBALS['y'];
echo $GLOBALS["y"] . "<br>";
}
myTest();
echo $x; // outputs 15
5 42
static keyword
When a function is completed/executed, all of its variables are deleted. However, sometimes
we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest(); // Outputs 0
myTest(); // Outputs 1
myTest(); // Outputs 2 //the out put is 012 what about the code of this out put?
?> Then, each time the function is called, that variable will still have the information it contained from the
last time the function was called. The variable is still local to the function.

43
Data Types

• PHP has a total of eight data types which we use to construct our variables:
integers, floats, Booleans, strings, arrays, objects, null, and resources.

• The first four are simple types, and the next two (arrays and
objects) are compound - the compound types can package up other arbitrary
values of arbitrary type, whereas the simple types cannot. The last two are
Special types.

• PHP has a useful function named var_dump() that prints the current data
type and value for one or more variables.
44
string
• A string is a sequence of characters, like "Hello world!".

• A string can be any text inside quotes.

• In PHP, a string is anything between matching quotes:

You can use single or double quotes:

• <?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>
45
Cont.…
• Singly quoted strings are treated almost literally, whereas doubly quoted
strings replace variables with their values as well as specially interpreting
certain character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>//My $variable will not print!\n
My name will print 46
String Concatenation Operator

• To concatenate two string variables together, use the dot (.) operator:

<?php

$string1="Hello World";

$string2="1234";

echo $string1 . " " . $string2;

?> Hello World 1234

47
integers

Integers: are whole numbers, without a decimal point, like 3214.


They are the simplest type. they correspond to simple whole
numbers, both positive and negative.

Integers can be assigned to variables, or they can be used in


expressions, like so:

48
Rules for integers
• An integer must have at least one digit

• An integer must not have a decimal point

• An integer can be either positive or negative

• Integers can be specified in: base 10, base 16, base 8, or base 2 notation
• <?php
$x = 5985;
var_dump($x);
?>

49
Float

• float (floating point number) is a number with a decimal point or a number


in exponential form.

• In the following example $x is a float. The PHP var_dump() function returns


the data type and value:

• <?php

• $x = 10.365;

• var_dump($x);

• ?> out put will be


50
Boolean
• A Boolean represents two possible states: TRUE or FALSE.

• $x = true;
$y = false;

• Booleans are often used in conditional testing.

• <?php

• $x=true;

• var_dump($x);

• ?> 51
Array
• An array is a data structure that stores one or more similar type of values in a
single value.

• An array stores multiple values in one single variable.

• In the following example $cars is an array.

• The PHP var_dump() function returns the data type and value:

• <?php

• $cars = array("Volvo", "BMW", "Toyota");

• var_dump($cars);

• ?> 52
Cont..
• <?php
• $cars = array("Volvo","BMW","Toyota"); <?php
• foreach ($cars as $key => $value) {
$cars = array("Volvo", "BMW", "Toyota");
• echo $value ."<br>";
echo $cars[0]."<br>";
• }
• //var_dump($cars); echo $cars[1]."<br>";
• ?> echo $cars[2]; //Method 1 to create an array
?>

• <?php
• $cars = array("Volvo","BMW","Toyota");
• foreach ($cars as $key => $value) {
• echo $key." ". $value ."<br>";
• }
• //var_dump($cars);
• ?> 53
Cont.…

• There are three different kind of arrays and each array value is accessed using an
ID which is called array index.

– Numeric array - An array with a numeric index. Values are stored and accessed
in linear fashion.

– Associative array - An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.

– Multidimensional array - An array containing one or more arrays and values


are accessed using multiple indices
54
Numeric Array

• These arrays can store numbers, strings and any object but their index will
be presented by numbers. By default array index starts from zero.

• It is known Indexed arrays.

Example

• Following is the example showing how to create and access numeric arrays.

• Here we have used array() function to create array.

55
Cont.…
<?php /* Second method to create array. */
/* First method to create array. */ <?php
$numbers = array( 1, 2, 3, 4, 5); $numbers[0] = 1;
foreach( $numbers as $value ) $numbers[1] = 2;
{ $numbers[2] = 3;
echo "Value is $value <br/>"; $numbers[3] = 4;
} // out puts are $numbers[4] = 5;
foreach( $numbers as $value ){
echo "Value is". $value ."<br/>";
}
?>
56
Associative Arrays
• The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index.

• Associative array will have their index as string so that you can establish a
strong association between key and values.
• There are two ways to create an associative array:
• //The first method to create this array
<?php

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

echo "Peter is " . $age['Peter'] . " years old.";


57
?>//out put
Cont.…
//second method to create Associative array is
<?php

$age['Peter'] = "35";

$age['Ben'] = "37";

$age['Joe'] = "43";

echo " Age of Peter is". $age ['Peter'] ."<br />";

echo " Age of Ben is". $age ['Ben'] ."<br />";

echo " Age of Jon is". $age ['Joe'] ;

?> output is
58
Multidimensional Arrays
• A multi-dimensional 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.

• Values in the multi-dimensional array are accessed using multiple index.

Example

• In this example we create a two dimensional array to store marks of three


students in three subjects:

• This example is an associative array, you can create numeric array in the same
fashion.
59
Cont.…
<?php
$marks = array( "mohammad" => array("physics" => 35,"maths" => 30,"chemistry" =>39),
"qadir" => array ( "physics" => 30, "maths" => 32, "chemistry" => 29 ),
"zara" => array ("physics" => 31, "maths" => 22, "chemistry" => 39 ) );

/*Accessing multi-dimensional array values */


echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?> 60
PHP Sorting Arrays
• The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.

• PHP - Sort Functions For Arrays


•sort() - sort arrays in ascending order
•rsort() - sort arrays in descending order
•asort() - sort associative arrays in ascending order, according to the value
•ksort() - sort associative arrays in ascending order, according to the key
•arsort() - sort associative arrays in descending order, according to the value
•krsort() - sort associative arrays in descending order, according to the key
61
Sort Array in Ascending Order - sort()
• <?php
• $cars = array ("Volvo", "BMW", "Toyota");
• sort($cars);
• for ($i=0; $i < count($cars); $i++) {
• echo $cars[$i] . "<br>";
• }
• ?> //
• <?php
$numbers =array(4,6,2,22,11);
sort($numbers);
for ($i=0; $i <count($numbers)-1 ; $i++) {
echo $numbers[$i] . "<br>";
}
62
?>//
Sort Array in Descending Order - rsort()
• <?php
• $cars = array ("Volvo", "BMW", "Toyota");
• rsort($cars);
• for ($i=0; $i < count($cars); $i++) {
• echo $cars[$i] . "<br>";
• }
• ?>

• <?php
• $numbers=array(4, 6, 2, 22, 11);
• rsort($numbers);
• for($i=0;$i<count($numbers)-1;$i++)
• echo $numbers[$i]."<br>";
• ?>
63
Sort Array (Ascending Order), According to Value - asort()
• <?php
• $course= array("OS"=>"50", "IP"=>"40", "SAD"=>"60");
• asort($course);
• foreach($course as $x => $x_value) {
• echo $x_value ;
• }
• ?> out put=405060
• Sort Array (Ascending Order), According to Key - ksort()
• <?php
• $course= array("OS"=>"50", "IP"=>"40", "SAD"=>"60");
• ksort($course);
• foreach($course as $x => $x_value) {
• echo $x . "<br>";
• }
• ?> 64
Sort Array (Descending Order), According to Value - arsort()
• <?php
• $course= array("OS"=>"50", "IP"=>"40", "SAD"=>"60");
• arsort($course);
• foreach($course as $x => $x_value) {
• echo $x_value . "<br>";
• }
• ?>

• Sort Array (Descending Order), According to Key - krsort()


• <?php
• $course= array("OS"=>"50", "IP"=>"40", "SAD"=>"60");
• krsort($course);
• foreach($course as $x => $x_value) {
• echo $x . "<br>";
• }
• ?> 65
Object

• Classes and objects are the two main aspects of object-oriented programming.

• Class is a group of similar objects or it is a template for objects.

• A class is a structure that can contain properties and methods.

• An object is a data type which stores data and information on how to process that
data. An object is an instance of a class.

• Logical vs physical entity respectively.

• Class {} vs new () keyword .

• Object is a real world entity such as apple, mango, papaya, etc.


66
Null
• Null is a special data type which can have only one value: NULL.

• A variable of data type NULL is a variable that has no value assigned to it.

• Tip: If a variable is created without a value, it is automatically assigned a value of NULL.

• Variables can also be emptied by setting the value to NULL:

• Example
• <?php
• $x = "Hello world!"; string(12) "Hello world!"
• $y = null; How can yow write the php code, if the output is= Hello world!"; ?
• var_dump($x);
• ?>
• // string(12) "Hello world!“
67
Resource

• The special resource type is not an actual data type.

• It is the storing of a reference

• To functions and resources external to PHP.

• A common example of using the resource data type is a database call.

68
.
PHP String Functions
Commonly used functions to manipulate strings.
1. strlen()

• The PHP strlen() function returns the length of a string.

<?php

echo strlen("Hello world!");

?>// outputs 12

2. str_word_count()

The PHP str_word_count() function counts the number of words in a string.

<?php

echo str_word_count("string is sequence of character ")


69
?>// output 5
Cont..
3. strrev() The PHP strrev() function reverses a string.
Reverse the string " Internet Programming"
<?php
echo strrev("Internet Programming");
?>//
4. strpos() searches for a specific text within a string. If a match is found, the function returns the character
position of the first match. If no match is found, it will return FALSE.
• Search for the text "world" in the string "Hello world!":
• <?php
echo strpos("Hello world!", "world"); // outputs 6 word and w have the same position =6
?>
• echo strpos("Hello World",“H"); // outputs ?
• echo strpos("Hello World",“o"); // outputs ?
• echo strpos("Hello World",“E"); // outputs ?
• echo strpos("Hello World", " "); // outputs ?
• echo strpos("Hello World", "Hello");// outputs ? 70
Cont..
5. str_replace() replaces some characters with some other characters in a string.

• Replace the text "world" with "Center“

Syntax: echo str_replace(search, replace, subject)

• <?php
echo str_replace("world", "Center", " Hello world") ."<br>";
?> // outputs Hello Center!

• echo str_replace("World", "Center","Hello Ethiopia!");

• echo str_replace("Hello", "Ethiopia"," Ethiopia Hello !");

• echo str_replace("Hello", "Center","Hello Ethiopia!");

• echo str_replace("Hello", "Center"," Ethiopia Hello !"); 71


Cont..
6. strtoupper() : translates the given all characters to UPPER case.
• <?php
• echo strtoupper("Hello Ethiopia!"); // HELLO ETHIOPIA!
• ?>
7. strtolower() : translates the given all characters to lower case.
• <?php
• echo strtolower("Hello Ethiopia!"); // hello ethiopia!
• ?>
8. str_repeat(): allow us to duplicate the string based on the second argument.
Syntax: echo str_repeat (input, multiplier)
<?php
echo str_repeat("Technology "."<br>","4"); //
?> 72
PHP Numbers

• One thing to notice about PHP is that it provides automatic data type
conversion.

• So, if you assign an integer value to a variable, the type of that variable will
automatically be an integer. Then, if you assign a string to the same variable,
the type will change to a string.

• This automatic conversion can sometimes break your code.

73
PHP Integers
• An integer is a number without any decimal part.

• 2, 256, -256, 10358, -179567 are all integers. While 7.56, 10.0, 150.67 are
floats.

• So, an integer data type is a non-decimal number

• 4 * 2.5 is 10, the result is stored as -------?, because one of the operands is a ---
----- (-----).
• PHP has the following functions to check if the type of a variable is integer:
• is_int()
• is_integer() - alias of is_int()
• is_long() - alias of is_int() 74
Cont..
• Example

• Check if the type of a variable is integer:

• <?php
$x = 5985;
var_dump(is_int($x));
$x = 59.85;
var_dump(is_int($x));
?>// outputs

75
PHP Floats
• A float is a number with a decimal point or a number in exponential form.

• 2.0, 256.4, 10.358, 7.64E+5, 5.56E-5 are all floats.

• The float data type can commonly store a value up to


1.7976931348623E+308 (platform dependent), and have a maximum
precision of 14 digits.

• PHP has the following functions to check if the type of a variable is float:

• is_float() • <?php
$x = 10.365;
• is_double() - alias of is_float() var_dump(is_float($x));
?>// 76
PHP Infinity
• A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.

• PHP has the following functions to check if a numeric value is finite or infinite:
• is_finite()
• is_infinite()
• Example:
• Check if a numeric value is finite or infinite:
• <?php
$x = 1.9e411;
var_dump($x);
?>// output is

77
PHP Numerical Strings
• The PHP is_numeric() function can be used to find whether a variable is
numeric. The function returns true if the variable is a number or a numeric
string, false otherwise.
• Check if the variable is numeric:
• <?php
• $x =5985;
• var_dump(is_numeric($x)) ;
• $x ="5985.5";
• var_dump(is_numeric($x)) ;
• $x ="Hello";
• var_dump(is_numeric($x));
• ?>
78
PHP Casting Strings and Floats to Integers
• Sometimes you need to cast a numerical value into another data type.
• The (int), (integer), or intval() function are often used to convert a value to an integer.
• Cast float and string to integer:
• <?php
// Cast float to int
$x = 23465.768;
$int_cast = (int)$x;
echo $int_cast;
echo "<br>";
// Cast string to int
$x = "23465.768";
$int_cast = (int)$x;
echo $int_cast;
?>//
79
PHP Math

• PHP has a set of math functions that allows you to perform mathematical tasks
on numbers.
1. pi() Function:The pi() function returns the value of PI:
<?php
echo(pi()); // returns 3.1415926535898
?>
2. min() and max() Functions:The min() and max() functions can be used to find
the lowest or highest value in a list of arguments:
<?php
echo(min(0,150,30,20,-8,-200)."<br>");
echo(max(0,150,30,20,-8,-200));
?> 80
Cont.
3. abs() Function: The abs() function returns the absolute (positive) value of a
number:
<?php
echo(abs(-6.7)); // returns 6.7
?>
4. sqrt() Function: The sqrt() function returns the square root of a number:
<?php
echo(sqrt(64)); // returns 8
?>
81
Cont.
5. round() Function: The round() function rounds a floating-point number to its
nearest integer:

<?php
echo(round(0.60)); // returns 1
echo(round(0.49)); // returns 0
?>

6.Random Numbers: The rand() function generates a random number:


<?php
echo(rand());
82
?>
Cont..
To get more control over the random number, you can add the
optional min and max parameters to specify the lowest integer and the highest
integer to be returned.
For example, if you want a random integer between 10 and 30 (inclusive),
use rand(10, 100):
<?php
echo(rand(10, 300));
?>

83
Constants
• A constant is a name or an identifier for a simple value. A constant value cannot
change during the execution of the script.

• By default a constant is case-sensitive. By convention, constant identifiers are


always uppercase.

• A constant name starts with a letter or underscore, followed by any number of


letters, numbers, or underscores.

• If you have defined a constant, it can never be changed or undefined.

Syntax:

• define(name, value, case-sensitive) 84


Cont..
• To define a constant you have to use define() function and to retrieve the
value of a constant, you have to simply specifying its name. Unlike with
variables, you do not need to have a constant with a $.

• You can also use the function constant() to read a constant's value if you
wish to obtain the constant's name dynamically.

• constant() function

• As indicated by the name, this function will return the value of the constant.

85
Cont…
• Parameters:

• name: Specifies the name of the constant

• value: Specifies the value of the constant

• case-insensitive: Specifies whether the constant name


should be case-insensitive. Default is false
• Create a constant with a case-sensitive name:
• <?php • Create a constant with a case-insensitive name:
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING; • <?php
?>// define("GREETING", "Welcome to
W3Schools.com!", true);
echo greeting;
?>//
86
PHP Constant Arrays
In PHP, you can create an Array constant using the define() function.

Create an Array constant:


<?php
define("cars", [ "Alfa Romeo", "BMW", "Toyota"]);
echo cars[0];
?>//

87
Cont..

• Constants are Global.

• Constants are automatically global and can be used across the entire script.
• This example uses a constant inside a function, even if it is defined outside
the function:
• <?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();

?>// 88
Cont.…

• Differences between constants and variables are

• There is no need to write a dollar sign ($) before a constant, where as in


Variable one has to write a dollar sign.

• Constants cannot be defined by simple assignment, they may only be


defined using the define() function.

• Constants may be defined and accessed anywhere without regard to variable


scoping rules.

• Once the Constants have been set, may not be redefined or undefined.
89
PHP Operators
• Operators are used to perform operations on variables and values.

• PHP divides the operators in the following groups:

• Arithmetic operators

• Assignment operators

• Comparison operators

• Increment/Decrement operators

• Logical operators

• String operators

• Array operators

• Conditional assignment operators 90


Cont…
Read Read Read more!!!

Reading Assignment

 PHP Operators

 PHP Conditional Statements

91
Questions?

92

You might also like