Professional Documents
Culture Documents
Notes
Notes
Notes
PHP
LEVEL 6 /YEAR 2 IT
PURPOSE STATEMENT
1. What is PHP
PHP is an open-source, interpreted, and object-oriented scripting
language that can be executed at the server-side.
PHP is well suited for web development.
Therefore, it is used to develop web applications (an application that
executes on the server and generates the dynamic page.)
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market
in 1995.
SOME IMPORTANT POINTS NEED TO BE
NOTICED ABOUT PHP
PHP stands for Hypertext Preprocessor.
There are many AMP options available in the market that are given below:
WAMP for Windows
LAMP for Linux
MAMP for Mac
SAMP for Solaris
FAMP for FreeBSD
XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform:
It includes some other components too such as FileZilla, OpenSSL, Webalizer,
Mercury Mail.
Download and Install XAMPP Server
Link: https://www.apachefriends.org/download.html
Step 1: Click on the above link provided to download the XAMPP
server according to your window requirement.
Step 2: After downloading XAMPP, double click on the downloaded file and
allow XAMPP to make changes in your system. A window will pop-up, where
you have to click on the Next button.
Step 3: Here, select the components, which you want to install and click Next.
Step 4: Choose a folder where you want to install the XAMPP in your system and
click Next.
Step 5: Click Next and move ahead.
Step 6: XAMPP is ready to install, so click on the Next button and install the
XAMPP.
Step 8: Choose your preferred language.
All PHP code goes between the php tag. It starts with <?php and ends with ?>. The
syntax of PHP tag is given below:
• <!DOCTYPE>
• <html>
• <body>
• <?php
• echo "<h2>Hello First PHP</
h2>";
• ?>
• </body>
• </html>
4. PHP Case Sensitivity
In PHP, keyword (e.g., echo, if, else, while), functions, user-defined functions, classes are not
case-sensitive. However, all variable names are case-sensitive.
In the below example, you can see that all three echo statements are equal and valid:
<!DOCTYPE>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World using echo<br>";
ECHO "Hello World using ECHO<br>";
EcHo "Hello World using EcHo<br>";
?>
</body>
Look at the below example that the variable names are case sensitive.
You can see the example below that only the second statement will display the
value of the $color variable. Because it treats $color, $ColoR, and $COLOR as
three different variables:
<!DOCTYPE html>
<html>
<body>
<?php
$color = “black";
echo "My car is " . $coloR . "<br>";
echo "My dog is " . $color . "<br>";
echo "My phone is " . $COLOR . "<br>";
?>
</body>
</html>
6. PHP Echo
PHP echo is a language construct, not a function. Therefore, you don't need to use parenthesis
with it. But if you want to use more than one parameter, it is required to use parenthesis.
PHP echo statement can be used to print the string, multi-line strings, escaping characters,
variable, array, etc. Some important points that you must know about the echo statement are:
<?php <?php
echo "Hello by PHP echo"; echo"Hello by PHP echo
?> this is multi line
text printed by
PHP echo statement ";
?>
PHP echo: printing escaping characters PHP echo: printing variable value
<?php
<?php
echo "Hello escape \"sequence\" charact
ers"; $msg="Hello JavaTpoint PHP";
?> echo "Message is: $msg";
?>
Difference between echo and print echo
Echo and print are language constructs, and they never behave like a function. Therefore, there is
no requirement for parentheses. However, both the statements can be used with or without
parentheses. We can use these statements to output variables or strings
print
print is also a statement, used as an alternative to
echo echo at many times to display the output.
echo is a statement, which is used to display print can be used with or without parentheses.
the output. print always returns an integer value, which is 1.
echo can be used with or without parentheses. Using print, we cannot pass multiple arguments.
echo does not return any value. print is slower than echo statement.
We can pass multiple strings separated by
comma (,) in echo.
echo is faster than print statement.
You can see the difference between echo and print statements with the help of the following
programs.
<?php
$fname = "Gunjan";
$lname = "Garg";
echo "My name is: ".$fname,$lname;
?>
It will generate a syntax error because of multiple arguments in a print statement.
<?php
$fname = "Gunjan";
$lname = "Garg";
print "My name is: ".$fname,$lname;
?>
OUTPUT
For Example (Check Return Value)
Echo statement does not return any value.
OUTPUT
As we already discussed that print returns a value, which is always 1.
<?php
$lang = "PHP";
$ret = print $lang." is a web development language.";
print "</br>";
print "Value return by print statement: ".$ret;
?>
OUTPUT
7. PHP Variables
In PHP, a variable is declared using a $ sign followed by the variable name.
A variable must start with a dollar ($) sign, followed by the variable name.
It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
One thing to be kept in mind that the variable name cannot start with a number or special
symbols.
PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.
PHP Variable: Declaring string, integer, and float
Let's see the example to store string, integer, and float values in PHP variables.
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
8. PHP Comments
A comment in PHP code is a line that is not executed as a part of the program. Its only
purpose is to be read by someone who is looking at the code.
Remind yourself of what you did. Most programmers have experienced coming back to their
own work a year or two later and having to re-figure out what they did. Comments can remind
you of what you were thinking when you wrote the code
Syntax for single-line comments Syntax for multiple-line comments
<?php <?php
// This is a single-line comment /*
This is a multiple-lines
# This is also a single-line comment block
comment that spans over multiple
?> lines
*/
</body> ?>
</html>
</body>
</html>
.
9. PHP Strings
A string is a sequence of characters, like "Hello world!".
Example
<?php
echo strlen("Hello world!"); // outputs 12
?>
str_word_count() - Count Words in a String
Example
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
strrev() - Reverse a String
The PHP strrev() function reverses a string.
Example
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
str_replace() - Replace Text Within a String
The PHP str_replace() function replaces some characters with some other
characters in a string.
Example
Replace the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!");
// outputs Hello Dolly!
?>
10. 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.
PHP Integers
2, 256, -256, 10358, -179567 are all integers.
An integer data type is a non-decimal number between -2147483648 and 2147483647 in 32 bit systems,
and between -9223372036854775808 and 9223372036854775807 in 64 bit systems.
A value greater (or lower) than this, will be stored as float, because it exceeds the limit of an integer.
Note: Another important thing to know is that even if 4 * 2.5 is 10, the result is stored as float,
because one of the operands is a float (2.5).
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));
?>
PHP Floats
A float is a number with a decimal point or a number in exponential form.
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 predefined constants for floats (from PHP 7.2):
PHP_FLOAT_DIG - The number of decimal digits that can be rounded into a float and back without
precision loss
is_float()
Example
$x = 10.365;
var_dump(is_float($x));
?>
PHP Infinity
A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.
Example
Check if a numeric value is finite or infinite:
<?php
$x = 1.9e411;
var_dump($x);
?>
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.
Example
Example
1. PHP pi() Function
<?php
The pi() function returns the value of PI:
echo(min(0, 150, 30, 20, -8, -200)); //
Example returns -200
<?php echo(max(0, 150, 30, 20, -8, -200)); //
3.1415926535898 ?>
?>
3. PHP abs() Function 4. PHP sqrt() Function
The abs() function returns the absolute The sqrt() function returns the square
(positive) value of a number: root of a number:
Example
<?php Example
?>
5. PHP round() Function 6. Random Numbers
The round() function rounds a floating- The rand() function generates a random number:
point number to its nearest integer: Example
<?php
echo(rand());
Example
?>
<?php
To get more control over the random number, you can add the
optional min and max parameters to specify the lowest integer
echo(round(0.60)); // returns 1 and the highest integer to be returned.
?>
12. PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
Arithmetic operators 8
Assignment operators 7
Comparison operators 6
Increment/Decrement operators 5
Logical operators 4
String operators 3
Array operators 2
Conditional assignment operators 1
1. PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
2. PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
3. PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value
of the assignment expression on the right.
4. PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
5. PHP Increment / Decrement Operators
PHP has two operators that are specially designed for strings.
8. PHP Array Operators
The PHP conditional assignment operators are used to set a value depending on conditions:
BACKEND DEVELOPMENT USING PHP
PHP CONTROL STATEMENT
1. PHP Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
if...else statement - executes some code if a condition is true and another code if that condition
is false
if...elseif...else statement - executes different codes for more than two conditions
Syntax
if (condition) {
code to be executed if condition is true;
}
Example
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
Syntax otherwise:
<?php
if (condition) {
$t = date("H");
code to be executed if condition is
if ($t < "20") {
true;
echo "Have a good day!";
} else {
} else {
code to be executed if condition is
echo "Have a good night!";
false;
}
}
?>
1.3. PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this
condition is true;
} else {
code to be executed if all conditions are false;
}
Example
the current time is less than 20. echo "Have a good day!";
Loops are used to execute the same block of code again and again, as long as a certain condition is
true.
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the specified
condition is true
do {
do { echo "The number is: $x
echo "The number is: $x <br>";
<br>"; $x++;
1 While loop is entry control loop Do-while loop is exit control loop
3 It test the condition before It test the condition ate the end of the
executing the loop body loop body
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
Example 1
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 10; - Continue the loop as long as $x is less than or equal to 10
$x++ - Increase the loop counter value by 1 for each iteration
This example counts to 100 by tens:
Example 2
<?php
for ($x = 0; $x <= 100; $x+=10) {
echo "The number is: $x <br>";
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 100; - Continue the loop as long as $x is less than or equal to 100
$x+=10 - Increase the loop counter value by 10 for each iteration
4. PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax
foreach ($array as $value) {
code to be executed;
}
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.
Examples
The following example will output the values of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
The following example will output both the keys and the values of the given array
($age):
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
<?php
We have already seen the break
for ($x = 0; $x < 10; $x+
statement used in an earlier chapter
+) {
which switch statement.
if ($x == 4) {
The break statement can also be used
break;
to jump out of a loop.
}
This example jumps out of the loop echo "The number is: $x
when x is equal to 4: <br>";
}
?>
<?php
PHP Continue for ($x = 0; $x < 10;
The continue statement breaks one $x++) {
iteration (in the loop), if a specified if ($x == 4) {
condition occurs, and continues with continue;
the next iteration in the loop. }
This example skips the value of 4: echo "The number is:
$x <br>";
}
?>
<?php
Break and Continue in While
$x = 0;
Loop
You can also use break and
while($x < 10) {
continue in while loops:
if ($x == 4) {
break;
Break Example }
echo "The number is: $x <br>";
$x++;
}
?>
<?php
$x = 0;
while($x < 10) {
Continue Example if ($x == 4) {
$x++;
continue;
}
echo "The number is: $x <br>";
$x++;
}
?>
1. PHP Functions
PHP function is a piece of code that can be reused many times.
Conditional function
Recursive function.
2. Advantage of PHP Functions
Code Reusability: PHP functions are defined only once and can be invoked
many times, like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic
many times. By the use of function, you can write the logic only once and
reuse it.
Syntax
function functionname(){
//code to be executed
}
Note: Function name must be start with letter and underscore only like
other labels in PHP. It can't be start with numbers or special symbols.
PHP Functions Example
PHP Function Arguments
<?php We can pass the information in PHP
function sayHello(){ function through arguments which is
echo "Hello PHP Function";
separated by comma. PHP supports:
}
sayHello();// Call by Value (default),
calling function
?> Call by Reference,
Output: Default argument values
Hello PHP Function Variable-length argument list.
Let's see the example to pass single Let's see the example to pass two argument
argument in PHP function. in PHP function.
<?php <?php
function sayHello($name){
function sayHello($name,$age){
echo "Hello $name, you are $age year
echo "Hello $name<br/>";
s old<br/>";
} }
sayHello(“Emmy"); sayHello(“Emmy",27);
sayHello(“Kalisa"); sayHello(“Kalisa",29);
sayHello(“Josh");
sayHello("Josh",23);
?>
?>
Output:
Output:
Hello Emmy, you are 27 years old
Hello Emmy Hello Kalisa, you are 29 years old
Hello Kalisa Hello Josh, you are 23 years old
3. PHP Call By Reference
Value passed to the function doesn't modify the <?php
We can specify a default argument value in function. While calling PHP function if
you don't specify any argument, it will take the default argument.
Let's see a simple example of using default argument value in PHP function.
<?php
function sayHello($name=“Josh"){
echo "Hello $name<br/>"; Output:
}
Hello Deborah
sayHello(“Deborah");
Hello Josh
sayHello();//passing no value
Hello Ismael
sayHello(“Ismael");
?>
5. PHP Function: Returning Value
Output:
Cube of 3 is: 27