Unit 1_Web
Unit 1_Web
□ Introduction to PHP
□ PHP configuration in IIS & Apache Web server
□ Understanding of PHP.INI file
□ Understanding of PHP .htaccess file
□ PHP Variable
□ Static & global variable
□ GET & POST method
□ PHP Operator
□ Conditional Structure & Looping Structure
□ Array
□ User Defined Functions:
- argument function
- default argument
- variable function
- return function
□ Variable Length Argument Function
- func_num_args
- func_get_arg, func_get_args
□ Built in Functions
- Variable Functions
- String Function
- Math Function
- Date Function
- Array Function
- Miscellaneous Function
- File handling Function
Introduction to PHP
What is PHP?
Why use PHP?
Where is PHP?
PHP Features
Advantage of PHP
Disadvantage of PHP
How PHP Works?
What is PHP?
Why PHP?
Performance:
PHP script is executed much faster than those scripts which are written in other languages such
as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the versions
of PHP according to your requirement without paying any cost. All its components are free to
download and use.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at runtime.
E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
PHP allows us to use a variable without declaring its datatype. It will be taken automatically at
the time of execution based on the type of data it contains on its value.
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS,
etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same
work in a few lines of code. It has maximum control over the websites like you can make changes
easily whenever you want.
It has a large community of developers who regularly updates documentation, tutorials, online
help, and FAQs. Learning PHP from the communities is one of the significant benefits.
Web Development
PHP is widely used in web development now a days. PHP can develop dynamic websites easily.
But you must have the basic the knowledge of following technologies for web development as
well.
HTML
CSS
JavaScript
Ajax
XML and JSON
jQuery
Prerequisite
Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript. So, learn
these technologies for better implementation of PHP.
Audience
Our PHP tutorial is designed to help beginners and professionals. This PHP tutorial will help
those who are unaware about the concepts of PHP but have basic knowledge of computer
programming.
PHP configuration in IIS & Apache Web server
Install PHP
● To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It
is available for all operating systems. There are many AMP options available in the
market that are given below:
● WAMP for Windows
● LAMP for Linux
● MAMP for Mac
● XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some
other components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail, etc.
If you are on Windows and don't want Perl and other features of XAMPP, you should go
for WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.
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 wills 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 7: A finish window will display after successful installation. Click on the Finish button.
Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run the php program on
the localhost.
● Create a file and write HTML tags + PHP code and save this file with .php extension.
● PHP statements ends with semicolon (;).
● All PHP code goes between the php tag.
<?php
//your code here
?>
Step 2: Save the file with hello.php name in the htdocs folder, which resides inside the xampp
folder.
Note: PHP program must be saved in the htdocs folder, which resides inside the xampp
folder, where you installed the XAMPP. Otherwise it will generate an error - Object not
found.
Step 3: Run the XAMPP server and start the Apache and MySQL.
Step 4: Now, open the web browser and type localhost http://localhost/hello.php on your
browser window.
Step 5: The output for the above hello.php program will be shown as the screenshot below:
Most of the time, PHP programs run as a web server module. However, PHP can also be run on
CLI (Command Line Interface).
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:
INPUT OUTPUT
<!DOCTYPE> Hello world using echo
<html> Hello world using ECHO
<body> Hello world using EcHo
<?php
echo "Hello world using echo </br>";
ECHO "Hello world using ECHO </br>";
EcHo "Hello world using EcHo </br>";
?>
</body>
</html>
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:
Input Output
<html> Notice: Undefined variable: ColoR in
<body> D:\xampp\htdocs\program\p2.php on line 8
<?php My car is
$color = "black"; My dog is black
echo "My car is ". $ColoR ."</br>";
echo "My dog is ". $color ."</br>"; Notice: Undefined variable: COLOR in
echo "My Phone is ". $COLOR ."</br>"; D:\xampp\htdocs\program\p2.php on line
?> 10
</body> My Phone is
</html>
Only $color variable has printed its value, and
other variables $ColoR and $COLOR are
declared as undefined variables. An error has
occurred in line 5 and line 7.
Both of them are used for making changes to the PHP settings.
.htaccess –
A special file that can be used to change or manage the behavior of a website. Directing all
users to one page and redirecting the domain’s page to https or www are two of the most
important uses of the file. For .htaccess to work, PHP needs to be installed as an Apache module.
php.ini –
This special file allows making changes to the default PHP settings. Either the default
php.ini file can be edited, or a new file can be created with relevant additions and then saved as
the php.ini file. For php.ini to work, PHP needs to run as CGI.
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:
echo is a statement, which is used to display the output.
echo can be used with or without parentheses: echo(), and echo.
echo does not return any value.
We can pass multiple strings separated by a comma (,) in echo.
File: echo1.php
Input output
<?php Hello by PHP echo
echo "Hello by PHP echo"; PHP echo: printing multi line string
PHP Variable
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some
important points to know about variables:
o As PHP is a loosely typed language, so we do not need to declare the data types of the
variables. It automatically analyzes the values and makes conversions to its correct
datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.
$variablename=value;
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special
symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.
Let's see the example to store string, integer, and float values in PHP variables.
File: variable1.php
Input Output
<?php string is: hello string
integer is: 200
$str="hello string"; float is: 44.6
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
File: variable2.php
Input Output
1. <?php 11
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>
PHP Variable: case sensitive
In PHP, variable names are case sensitive. So variable name "color" is different from Color,
COLOR, COLor etc.
File: variable3.php
Input Output
1. <?php My car is red
Notice: Undefined variable: COLOR in
2. C:\wamp\www\variable.php on line 4
3. $color="red"; My house is
4. echo "My car is " . $color . "<br>"; Notice: Undefined variable: coLOR in
C:\wamp\www\variable.php on line 5
5. echo "My house is " . $COLOR . "<br>"; My boat is
6. echo "My boat is " . $coLOR . "<br>";
7.
8. ?>
File: variablevalid.php
Input Output
1. <?php hello
hello
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
?>
File: variableinvalid.php
Input Output
1. <?php Parse error: syntax error, unexpected '4'
(T_LNUMBER), expecting variable
2. $4c="hello";//number (invalid) (T_VARIABLE)
3. $*d="hello";//special symbol (invalid) or '$' in C:\wamp\www\variableinvalid.php
4. echo "$4c <br/> $*d"; on line 2
?>
The scope of a variable is defined as its range in the program under which it can be accessed. In
other words, "The scope of a variable is the portion of the program within which it is defined and
can be accessed."
1. Local variable
2. Global variable
3. Static variable
Local variable
The variables that are declared within a function are called local variables for that function.
These local variables have their scope only in that particular function in which they are declared.
This means that these variables cannot be accessed outside the function, as they have local
scope.
A variable declaration outside the function with the same name is completely different from the
variable declared inside the function. Let's understand the local variables with the help of an
example:
File: local_variable1.php
Input output
1. <?php Local variable declared
inside the function is: 45
2. function local_var()
3. {
4. $num = 45; //local variable
5. echo "Local variable declared inside the function is: ". $num;
6. }
7. local_var();
8. ?>
File: local_variable2.php
Input Output
1. <?php Web development language: PHP
Notice: Undefined variable: lang in
2. function mytest() D:\xampp\htdocs\program\p3.php on line 28
3. {
4. $lang = "PHP";
5. echo "Web development language: " .$lang;
6. }
7. mytest();
8. //using $lang (local variable) outside the f
unction will generate an error
9. echo $lang;
?>
Global variable
The global variables are the variables that are declared outside the function. These variables can
be accessed anywhere in the program. To access the global variable within a function, use the
GLOBAL keyword before the variable. However, these variables can be directly accessed or used
outside the function without any keyword. Therefore there is no need to use any keyword to
access a global variable outside the function.
Example:
File: global_variable1.php
Input Output
<?php Variable inside the function: Sanaya
Sharma
$name = "Sanaya Sharma"; //Global Variable Variable outside the function: Sanaya
function global_var() Sharma
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Note: Without using the global keyword, if you try to access a global variable inside the
function, it will generate an error that the variable is undefined.
Example:
File: global_variable2.php
Input output
<?php Notice: Undefined variable: name in
D:\xampp\htdocs\program\p3.php on line
$name = "Sanaya Sharma"; //global variable 6
function global_var() Variable inside the function:
{
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
?>
Another way to use the global variable inside the function is predefined $GLOBALS array.
Example:
File: global_variable3.php
Input output
<?php Sum of global variables is: 18
$num1 = 5; //global variable
$num2 = 13; //global variable
function global_var()
{
$sum = $GLOBALS['num1'] + $GLOBALS['num2'];
echo "Sum of global variables is: " .$sum;
}
global_var();
?>
If two variables, local and global, have the same name, then the local variable has higher priority
than the global variable inside the function.
Example:
File: global_variable2.php
Input Output
<?php
Value of x: 7
$x = 5;
function mytest()
{
$x = 7;
echo "value of x: " .$x;
}
mytest();
?>
Note: local variable has higher priority than the global variable
Static variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed.
Sometimes we need to store a variable even after completion of function execution. Therefore,
another important feature of variable scoping is static variable. We use the static keyword before
the variable to define a variable, and this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program
execution leaves the scope. Understand it with the help of an example:
Example:
File: static_variable.php
Input Output
<?php Static: 4
Non-static: 7
function static_var() Static: 5
{ Non-static: 7
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}
//first function call
static_var();
//second function call
static_var();
?>
You have to notice that $num1 regularly increments after each function call, whereas $num2
does not. This is why because $num1 is not a static variable, so it freed its memory after the
execution of each function call.
PHP Comments
PHP comments can be used to describe any line of code so that other developer can understand
the code easily. It can also be used to hide any code.
PHP supports single line and multiline comments. These comments are similar to C/C++ and Perl
style (Unix shell style) comments.
Input Output
Welcome to PHP single line comments
1. <?php
2. // this is C++ style single line comment
3. # this is Unix Shell style single line comment
4. echo "Welcome to PHP single line comments";
5. ?>
In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */.
Let's see a simple example of PHP multiple line comment.
Input Output
Welcome to PHP multi line comment
<?php
/*
Anything placed
within comment
will not be displayed
on the browser;
*/
echo "Welcome to PHP multi line comment";
?>
Try out following example by putting the source code in test.php script.
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
</body>
</html>
It will produce the following result −
exit();
}
?>
<html>
<body>
</body>
</html>
It will produce the following result −
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We
will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.
It will produce the following result −
PHP Operator
PHP Operator is a symbol i.e used to perform operations on operands. In simple words,
operators are used to perform operations on variables or values. For example:
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
o Unary Operators: works on single operands such as ++, -- etc.
o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as
addition, subtraction, etc. with numeric values.
Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment
operator is "=".
Operator Name Example Explanation
Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.
& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of
comparison operators are given:
=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of same data
type
!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not of same
data type
<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b
>= Greater than or equal $a >= $b Return TRUE if $a is greater than or equal $b
to
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a
variable.
Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.
Xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
String Operators
The string operators are used to perform the operation on strings. There are two string
operators in PHP, which are given below:
.= Concatenation and $a .= $b First concatenate $a and $b, then assign the concatenated
Assignment string to $a, e.g. $a = $a . $b
Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the
values of arrays.
Operator Name Example Explanation
=== Identity $a === $b Return TRUE if $a and $b have same key/value pair of same type in
same order
Type Operators
The type operator instanceof is used to determine whether an object, its parent and its derived
class are the same type or not. Basically, this operator determines which certain class the object
belongs to. It is used in object-oriented programming.
Input Output
Charu is a developer.
<?php bool(true) bool(false)
//class declaration
class Developer
{}
class Programmer
{}
//creating an object of type Developer
$charu = new Developer();
Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell
command. Execution operator and shell_exec() give the same result.
`` backticks echo `dir`; Execute the shell command and return the result.
Here, it will show the directories available in current folder.
[ array() left
** arithmetic right
++ -- ~ (int) (float) (string) (array) (object) (bool) @ increment/decrement and types right
Instanceof types non-associative
| bitwise OR left
|| logical OR left
?: ternary left
Or logical left
PHP if else statement is used to test condition. There are various ways to use if statement in PHP.
o If
o if-else
o if-else-if
o nested if
PHP If Statement
If statement is used to executes the block of code exist inside the if statement only if the specified
condition is true.
Syntax
if(condition){
//code to be executed
}
Flowchart
Example
Input Output
12 is less than 100
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
Syntax
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
Flowchart
Example
Input Output
12 is even number
1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
?>
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can
check multiple conditions using this statement.
Syntax
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}
Flowchart
Example
Input output
B Grade
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.
Syntax
if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}
Flowchart
Example
Input Output
Eligible to give vote
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.
Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
We will pass a character in switch expression to check whether it is vowel or constant. If the
passed character is A, E, I, O, or U, it will be vowel otherwise consonant.
Input Output
Given character is vowel
<?php
$ch = 'U';
switch ($ch)
{
case 'a':
echo "Given character is vowel";
break;
case 'e':
echo "Given character is vowel";
break;
case 'i':
echo "Given character is vowel";
break;
case 'o':
echo "Given character is vowel";
break;
case 'u':
echo "Given character is vowel";
break;
case 'A':
echo "Given character is vowel";
break;
case 'E':
echo "Given character is vowel";
break;
case 'I':
echo "Given character is vowel";
break;
case 'O':
echo "Given character is vowel";
break;
case 'U':
echo "Given character is vowel";
break;
default:
echo "Given character is consonant";
break;
}
?>
PHP allows to pass string in switch expression. Let's see the below example of course duration
by passing string in switch case statement.
Input Output
B.Tech is 4 years course
<?php
$ch = "B.Tech";
switch ($ch)
{
case "BCA":
echo "BCA is 3 years course";
break;
case "Bsc":
echo "Bsc is 3 years course";
break;
case "B.Tech":
echo "B.Tech is 4 years course";
break;
case "B.Arch":
echo "B.Arch is 5 years course";
break;
default:
echo "Wrong Choice";
break;
}
?>
PHP switch statement is fall-through. It means it will execute all statements after getting the first
match, if break statement is not found.
Input Output
Choice c
<?php Choice d
$ch = 'c'; case a, b, c, and d is not found
switch ($ch)
{
case 'a':
echo "Choice a";
break;
case 'b':
echo "Choice b";
break;
case 'c':
echo "Choice c";
echo "</br>";
case 'd':
echo "Choice d";
echo "</br>";
default:
echo "case a, b, c, and d is not found";
}
?>
Nested switch statement means switch statement inside another switch statement. Sometimes it
leads to confusion.
Input Output
Hyundai Tucson price is 22.39 - 32.07 L.
<?php
$car = "Hyundai";
$model = "Tucson";
switch( $car )
{
case "Honda":
switch( $model )
{
case "Amaze":
echo "Honda Amaze price is 5.93 - 9.79 Lakh.";
break;
case "City":
echo "Honda City price is 9.91 - 14.31 Lakh.";
break;
}
break;
case "Renault":
switch( $model )
{
case "Duster":
echo "Renault Duster price is 9.15 - 14.83 L.";
break;
case "Kwid":
echo "Renault Kwid price is 3.15 - 5.44 L.";
break;
}
break;
case "Hyundai":
switch( $model )
{
case "Creta":
echo "Hyundai Creta price is 11.42 - 18.73 L.";
break;
case "Tucson":
echo "Hyundai Tucson price is 22.39 - 32.07 L.";
break;
case "Xcent":
echo "Hyundai Xcent price is 6.5 - 10.05 L.";
break;
}
break;
}
?>
It should be used if the number of iterations is known otherwise use while loop. This means for
loop is used when you already know how many times you want to execute a block of code.
It allows users to put all the loop related statements in one place. See in the syntax given below:
Syntax
for(initialization; condition; increment/decrement){
//code to be executed
}
Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the
following meanings:
initialization - Initialize the loop counter value. The initial value of the for loop is done only
once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the condition is
false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.
Flowchart
Example
Input output
1
1. <?php 2
2. for($n=1;$n<=10;$n++){ 3
4
5
3. echo "$n<br/>"; 6
4. } 7
?> 8
9
10
Example
All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't pass
parameters, it will execute infinite.
Input Output
1
<?php 2
$i = 1; 3
4
//infinite loop .
for (;;) { .
.
echo $i++;
echo "</br>";
}
?>
Example
Below is the example of printing numbers from 1 to 9 in four different ways using for loop.
Input Output
123456789
<?php 123456789
/* example 1 */ 123456789
123456789
for ($i = 1; $i <= 9; $i++) {
echo $i;
}
echo "</br>";
/* example 2 */
for ($i = 1; ; $i++) {
if ($i > 9) {
break;
}
echo $i;
}
echo "</br>";
/* example 3 */
$i = 1;
for (; ; ) {
if ($i > 9) {
break;
}
echo $i;
$i++;
}
echo "</br>";
/* example 4 */
for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);
?>
In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer
for loop is to be executed for 3 times and inner for loop for 3 times, inner for loop will be
executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer
loop).
Example
Input Output
11
1. <?php 12
2. for($i=1;$i<=3;$i++){ 13
21
3. for($j=1;$j<=3;$j++){ 22
4. echo "$i $j<br/>"; 23
31
5. } 32
33
6. }
7. ?>
PHP For Each Loop
The foreach loop is used to traverse the array elements. It works only on array and object. It will
issue an error if you try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate
the elements of an array.
Syntax
Example
Input Output
Season is: summer
1. <?php Season is: winter
2. $season=array("summer","winter","spring","autumn"); Season is: spring
Season is: autumn
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
There is one more syntax of foreach loop.
Syntax
foreach ($array as $key => $element) {
//code to be executed
}
Flowchart
Example 1:
PHP program to print array elements using foreach loop.
Input output
Summer
<?php Winter
//declare array Autumn
Rainy
$season = array ("Summer", "Winter", "Autumn", "Rainy");
//access array elements using foreach loop
foreach ($season as $element) {
echo "$element";
echo "</br>";
}
?>
Example 2:
PHP program to print associative array elements using foreach loop.
Input Output
Name : Alex
<?php Email : [email protected]
//declare array Age : 21
Gender : Male
$employee = array (
"Name" => "Alex",
"Email" => "[email protected]",
"Age" => 21,
"Gender" => "Male"
);
//display associative array element through foreach loop
foreach ($employee as $key => $element) {
echo $key . " : " . $element;
echo "</br>";
}
?>
Example 3:
Multi-dimensional array
Input Output
Alex Bob Camila Denial
<?php
//declare multi-dimensional array
$a = array();
$a[0][0] = "Alex";
$a[0][1] = "Bob";
$a[1][0] = "Camila";
$a[1][1] = "Denial";
//display multi-
dimensional array elements through foreach loop
foreach ($a as $e1) {
foreach ($e1 as $e2) {
echo "$e2\n";
}
}
?>
Example 4:
Dynamic array
Input Output
javatpoint
1. <?php
2. //dynamic array
3. foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) {
4. echo "$elements\n";
5. }
6. ?>
PHP While Loop
PHP while loop can be used to traverse set of code like for loop. The while loop executes a block
of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from the
body of loop.
The while loop is also called an Entry control loop because the condition is checked before
entering the loop body. This means that first the condition is checked. If the condition is true, the
block of code will be executed.
Syntax
while(condition){
//code to be executed
}
Alternative Syntax
while(condition):
//code to be executed
endwhile;
Alternative Example
Input Output
1
1. <?php 2
2. $n=1; 3
4
3. while($n<=10): 5
4. echo "$n<br/>"; 6
7
5. $n++; 8
9
6. endwhile; 10
7. ?>
Example
Below is the example of printing alphabets using while loop.
Input Output
A
1. <?php B
2. $i = 'A'; C
D
3. while ($i < 'H') { E
4. echo $i; F
G
5. $i++;
6. echo "</br>";
7. }
8. ?>
We can use while loop inside another while loop in PHP, it is known as nested while loop.
In case of inner or nested while loop, nested while loop is executed fully for one outer while loop.
If outer while loop is to be executed for 3 times and nested while loop for 3 times, nested while
loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times
for 3rd outer loop).
Example
Input Output
11
<?php 12
$i=1; 13
21
while($i<=3){ 22
$j=1; 23
31
while($j<=3){ 32
33
echo "$i $j<br/>";
$j++;
}
$i++;
}
?>
Syntax
while(true) {
//code to be executed
}
Example
Input Output
Hello Javatpoint!
<?php Hello Javatpoint!
while (true) { Hello Javatpoint!
Hello Javatpoint!
echo "Hello Javatpoint!"; .
echo "</br>"; .
.
} .
?> .
Hello Javatpoint!
Hello Javatpoint!
The PHP do-while loop is used to execute a set of code of the program several times. If you have
to execute the loop at least once and the number of iterations is not even fixed, it is
recommended to use the do-while loop.
It executes the code at least one time always because the condition is checked after executing the
code.
The do-while loop is very much similar to the while loop except the condition check. The main
difference between both loops is that while loop checks the condition at the beginning, whereas
do-while loop checks the condition at the end of the loop.
Syntax
do{
//code to be executed
}while(condition);
Flowchart
Example
Input Output
1
<?php 2
$n=1; 3
4
do{ 5
echo "$n<br/>"; 6
7
$n++; 8
9
}while($n<=10); 10
1. ?>
Example
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-
while loop, it is must that the program should not contain any other statements after the do-
while loop. In this case, it will not generate any error.
Input Output
Welcome to College!
<?php Welcome to College!
$x = 5; Welcome to College!
Welcome to College!
do { Welcome to College!
echo "Welcome to College! </br>";
$x++;
} while ($x < 10);
?>
Example
The following example will increment the value of $x at least once. Because the given condition is
false.
Input Output
1 is not greater than 10.
<?php 2
$x = 1;
do {
echo "1 is not greater than 10.";
echo "</br>";
$x++;
} while ($x > 10);
echo $x;
?>
The while loop is also named as entry control loop. The do-while loop is also named as exit control loop.
The body of the loop does not execute if the The body of the loop executes at least once, even if the
condition is false. condition is false.
Condition checks first, and then block of statements Block of statements executes first and then condition checks.
executes.
This loop does not use a semicolon to terminate the Do-while loop use semicolon to terminate the loop.
loop.
PHP Break
PHP break statement breaks the execution of the current for, while, do-while, switch, and for-
each loop. If you use break inside inner loop, it breaks the execution of inner loop only.
The break keyword immediately ends the execution of the loop or switch structure. It breaks the
current flow of the program at the specified condition and program control resumes at the next
statements outside the loop.
The break statement can be used in all types of loops such as while, do-while, for, foreach loop,
and also with switch case.
Syntax
jump statement;
break;
Flowchart
Let's see a simple example to break the execution of for loop if value of i is equal to 5.
Input Output
1
<?php 2
for($i=1;$i<=10;$i++){ 3
4
echo "$i <br/>"; 5
if($i==5){
break;
}
}
?>
The PHP break statement breaks the execution of inner loop only.
Input Output
11
<?php 12
for($i=1;$i<=3;$i++){ 13
21
for($j=1;$j<=3;$j++){ 22
31
echo "$i $j<br/>"; 32
if($i==2 && $j==2){ 33
break;
}
}
}
?>
The PHP break statement breaks the flow of switch case also.
Input Output
number is equal to 200
<?php
$num=200;
switch($num){
case 100:
echo("number is equals to 100");
break;
case 200:
echo("number is equal to 200");
break;
case 50:
echo("number is equal to 300");
break;
default:
echo("number is not equal to 100, 200 or 500");
}
?>
You can see in the above output, after getting the specified condition true, break statement
immediately ends the loop and control is came out from the loop.
It is not essential to break out of all cases of a switch statement. But if you want that only one
case to be executed, you have to use break statement.
Input Output
$car is not Mercedes Benz
<?php $car is Mercedes Benz
$car = 'Mercedes Benz';
switch ($car) {
default:
echo '$car is not Mercedes Benz<br>';
case 'Orange':
echo '$car is Mercedes Benz';
}
?>
The break accepts an optional numeric argument, which describes how many nested structures
it will exit. The default value is 1, which immediately exits from the enclosing structure.
Input Output
At matched condition i = 5
<?php At matched condition i = 10; quitting
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At matched condition i = 5<br />\n";
break 1; // Exit only from the switch.
case 10:
echo "At matched condition i = 10; quitting<br />\n";
break 2; // Exit from the switch and the while.
default:
break;
}
}?>
Note: The break keyword immediately ends the execution of the current structure.
The continue statement is used within looping and switch control structure when you
immediately jump to the next iteration.
The continue statement can be used with all types of loops such as - for, while, do-while, and
foreach loop. The continue statement allows the user to skip the execution of the code for the
specified condition.
Syntax
The syntax for the continue statement is given below:
jump-statement;
continue;
Flowchart:
Example
In the following example, we will print only those values of i and j that are same and skip others.
Input Output
11
<?php 22
//outer loop 33
Example
In the following example, we will print the even numbers between 1 to 20.
Input Output
Even numbers between 1 to
<?php 20:
//php program to demonstrate the use of continue statement 2
4
6
echo "Even numbers between 1 to 20: </br>"; 8
10
$i = 1; 12
14
while ($i<=20) { 16
if ($i %2 == 1) { 18
20
$i++;
continue; //here it will skip rest of statements
}
echo $i;
echo "</br>";
$i++;
}
?>
Example
The following example prints the value of array elements except those for which the specified
condition is true and continue statement is used.
Input Output
One
<?php Two
$number = array ("One", "Two", "Three", "Stop", "Four"); Three
Four
foreach ($number as $element) {
if ($element == "Stop") {
continue;
}
echo "$element </br>";
}
?>
The continue statement accepts an optional numeric value, which is used accordingly. The
numeric value describes how many nested structures it will exit.
Example
Input output
12
<?php 13
//outer loop 21
23
for ($i =1; $i<=3; $i++) { 31
//inner loop 32
?>
Array
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
PHP indexed array is an array which is represented by an index number by default. All elements
of array are represented by an index number which starts from 0.
PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as
numeric array.
Definition
There are two ways to define indexed array:
1st way:
$size=array("Big","Medium","Short");
2nd way:
$size[0]="Big";
$size[1]="Medium";
$size[2]="Short";
<?php
$size[0]="Big";
$size[1]="Medium";
$size[2]="Short";
echo "Size: $size[0], $size[1] and $size[2]";
?>
We can easily traverse array in PHP using foreach loop. Let's see a simple example to traverse all
the elements of PHP array.
File: array3.php
Input Output
Size is: Big
1. <?php Size is: Medium
2. $size=array("Big","Medium","Short"); Size is: Short
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>
Input Output
3
1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>
Definition
There are two ways to define associative array:
1st way:
1. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
2nd way:
1. $salary["Sonoo"]="550000";
2. $salary["Vimal"]="250000";
3. $salary["Ratan"]="200000";
Example
File: arrayassociative1.php
Input output
Sonoo salary: 550000
<?php Vimal salary: 250000
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000"); Ratan salary: 200000
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
File: arrayassociative2.php
Input Output
Sonoo salary: 550000
<?php Vimal salary: 250000
$salary["Sonoo"]="550000"; Ratan salary: 200000
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
Input Output
Key: Sonoo Value: 550000
<?php Key: Vimal Value: 250000
$salary=array("Sonoo"=>"550000","Vimal"= Key: Ratan Value: 200000
>"250000","Ratan"=>"200000");
foreach($salary as $k => $v) {
echo "Key: ".$k." Value: ".$v."<br/>";
}
?>
PHP Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data
in an array. PHP multidimensional array can be represented in the form of matrix which is
represented by row * column.
Definition
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
Id Name Salary
1 Sonoo 400000
2 John 500000
3 Rahul 300000
File: multiarray.php
Input Output
1 sonoo 400000
<?php 2 john 500000
$emp = array 3 rahul 300000
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument list
and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.
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
1. function functionname(){
2. //code to be executed
3. }
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.
File: functionarg.php
1. <?php
2. function sayHello($name){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Sonoo");
6. sayHello("Vimal");
7. sayHello("John");
8. ?>
Output:
Hello Sonoo
Hello Vimal
Hello John
File: functionarg2.php
1. <?php
2. function sayHello($name,$age){
3. echo "Hello $name, you are $age years old<br/>";
4. }
5. sayHello("Sonoo",27);
6. sayHello("Vimal",29);
7. sayHello("John",23);
8. ?>
Output:
Value passed to the function doesn't modify the actual value by default (call by value). But we
can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need to
use ampersand (&) symbol before the argument name.
File: functionref.php
Input Output
Hello Call By Reference
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
File: functiondefaultarg.php
Input output
Hello Rajesh
<?php Hello Sonoo
function sayHello($name="Sonoo"){ Hello John
File: functiondefaultarg.php
Input output
Cube of 3 is: 27
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
PHP Parameterized functions are the functions with parameters. You can pass any number of
parameters inside a function. These passed parameters act as variables inside your function.
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the function.
Input Output
<!DOCTYPE html>
<html>
<head>
<title>Parameter Addition and Subtraction Example</title>
</head>
<body>
<?php
//Adding two numbers
function add($x, $y) {
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(467, 943);
<?php
//add() function with two parameter
function add($x,$y)
{
$sum=$x+$y;
echo "Sum = $sum <br><br>";
}
//sub() function with two parameter
function sub($x,$y)
{
$sub=$x-$y;
echo "Diff = $sub <br><br>";
}
//call function, get two argument through input box and click on add or sub button
if(isset($_POST['add']))
{
//call add() function
add($_POST['first'],$_POST['second']);
}
if(isset($_POST['sub']))
{
//call add() function
sub($_POST['first'],$_POST['second']);
}
?>
<form method="post">
Enter first number: <input type="number" name="first"/><br><br>
Enter second number: <input type="number" name="second"/><br><br>
<input type="submit" name="add" value="ADDITION"/>
<input type="submit" name="sub" value="SUBTRACTION"/>
</form>
Output:
PHP allows you to call function by value and reference both. In case of PHP call by value, actual
value is not modified if it is modified inside the function.
Example 1
In this example, variable $str is passed to the adder function where it is concatenated with 'Call
By Value' string. But, printing $str variable results 'Hello' only. It is because changes are done in
the local variable $str2 only. It doesn't reflect to $str variable.
Input Output
Hello
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Example 2
Let's understand PHP call by value concept through another example.
Input output
10
<?php
function increment($i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
PHP Call By Reference
In case of PHP call by reference, actual value is modified if it is modified inside the function. In
such case, you need to use & (ampersand) symbol with formal arguments. The & represents
reference of the variable.
Input output
This is Call By Reference
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>
Example 2
Let's understand PHP call by reference concept through another example.
Input Output
11
<?php
function increment(&$i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
PHP Default Argument Values Function
PHP allows you to define C++ style default argument values. In such case, if you don't pass any
value to the function, it will use default argument value.
Let' see the simple example of using PHP default arguments in function.
Example 1
Input output
Hello Sonoo
1. <?php Hello Ram
2. function sayHello($name="Ram"){ Hello Vimal
Since PHP 5, you can use the concept of default argument value with call by reference also.
Example 2
Input Output
Greeting: Sonoo Jaiswal
<?php Greeting: Rahul Jaiswal
function greeting($first="Sonoo",$last="Jaiswal"){ Greeting: Michael Clark
$n3=$n1+$n2;
echo "Addition is: $n3<br/>";
}
add();
add(20);
add(40,40);
?>
PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.
The 3 dot concept is implemented for variable length argument since PHP 5.6.
INPUT OUTPUT
10
<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}
Description
mixed func_get_arg ( int $arg_num )
Gets the specified argument from a user-defined function's argument list. The argument
offset. Function arguments are counted starting from zero.
This function may be used in conjunction with func_get_args() and func_num_args() to allow
user-defined functions to accept variable-length argument lists.
Example:
INPUT OUTPUT
<?php Number of arguments: 3
function foo() Second argument is: 2
{
$numargs = func_num_args();
echo "Number of arguments: $numargs\n";
if ($numargs >= 2)
{
echo "Second argument is: " . func_get_arg(1) . "\n"; } }
foo(1, 2, 3); ?>
func_get_args
func_get_args — Returns an array comprising a function's argument list
Description
array func_get_args ( void )
Gets an array of the function's argument list.
This function may be used in conjunction with func_get_arg() and func_num_args() to allow user-
defined functions to accept variable-length argument lists.
Example:
Input Output
<?php Number of arguments: 3
function foo() Second argument is: 2
{ Argument 0 is: 1
$numargs = func_num_args(); Argument 1 is: 2
echo "Number of arguments: $numargs \n";
Argument 2 is: 3
if ($numargs >= 2)
{
echo "Second argument is: " . func_get_arg(1) . "\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++)
{
echo "Argument $i is: " . $arg_list[$i] . "\n";
}
}
foo(1, 2, 3); ?>
PHP Recursive Function
PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.
It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.
Example 1: Printing number
Input output
1
<?php 2
function display($number) { 3
4
if($number<=5){ 5
echo "$number <br/>";
display($number+1);
}
}
display(1);
?>
echo factorial(5);
?>
Built in Functions
Variable
Functions
gettype()
The gettype() function is used to get the type of a variable. The gettype() function gets the typeof variable;
gettype() is a function that display a data type.
Syntax:
gettype(var_name)
Parameter:
value
Possible values of the returned string:
boolean
integer
double
string
array
object
resource
NULL
unknown type
example
<?php
echo gettype(102).'<br>'; echo
gettype(true).'<br>'; echo
gettype(' ').'<br>'; echo
gettype(null).'<br>'; echo
gettype(array()).'<br>';
echo gettype(new stdclass());
?>
Output:
integer
boolean
string
NULL
array
object
settype()
The settype function sets the type of variable; the settype() function changes the data type.
Syntax:
settype(var_name, var_type)
Parameters:
/Optional
var_name The variable being converted. Required Mixed*
var_type Type of the variable. Possible values are : boolean, Optional String
integer, float, string, array, object, null.
*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.
Return value:
TRUE on success or FALSE on failure.
Value Type: Boolean.
Example:
<?php
$var1='98';
$var2='01';
settype($var1, "integer");
settype($var2, "integer");
echo ($var1.'<br>');
echo ($var2.'<br>');
echo ($var1+$var2.'<br>');
?>
Output:
98
1
99
Isset
The isset () function is used to check whether a variable is set or not. If a variable is already unset with
unset() function, it will no longer be set. The isset() function return false if testing variable contains a
NULL value.
Syntax:
isset(variable1, variable2 .............. )
Parameter:
Name Description Required Type
/Optional
variable1 The variable being checked Required Mixed*
*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.
Return value:
TRUE if variable (variable1,variable2..) exists and has value not equal to NULL, FALSEotherwise.
Value Type: Boolean.
Example:
<?php
$var1 = 'test';
var_dump(isset($var1));
?>
Output :
bool(true)
unset
The unset() function destroys a given variable.
Syntax:
unset (var1, var2 ........... )
Parameters:
Name Description Required / Type
Optional
/Optional
var_name The variable name. Required Mixed*
Return value:
The string value of var_name.
Value Type: String.
Example:
<?php
$var_name = 22.110; echo
strval ($var_name);
?>
Output:
22.11
floatval
The floatval() function is used to convert a value to a float.
Syntax:
floatval (var1)
Parameter:
var1 May be any scalar type. You cannot use floatval() on arrays Required Mixed*
or objects.
*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.Return
value:
The float value of the given variable.Value
Type: Float.
Example :
?php
$var_name1="122.00,50";
$var_name2="122.00";
$var_name3="122.50";
$var_name4="122,50";
$var_name5="122 50";
$var_name6="0.50";
$var_name7="0,50";
$var_name8="-122.50";
$var_name9="-122,50";
$var_name10="-122 50";
echo floatval($var_name1)."<br>"; echo
floatval($var_name2)."<br>"; echo
floatval($var_name3)."<br>"; echo
floatval($var_name4)."<br>"; echo
floatval($var_name5)."<br>"; echo
floatval($var_name6)."<br>"; echo
floatval($var_name7)."<br>"; echo
floatval($var_name8)."<br>"; echo
floatval($var_name9)."<br>"; echo
floatval($var_name10)."<br>";
?>
Output:
122
122
122.5
122
122
0.5
0
-122.5
-122
-122
intval
The intval() function is used to get the integer value of a variable.
Syntax:
intval(var_name, base)
Parameter:
base The base for the conversion. (default is base 10) Optional Integer
*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.Return value
The integer value of var on success, or 0 on failureValue
Type : Integer.
Example :
<?php
echo intval(102).'<br>'; echo
intval(102.22).'<br>';echo
intval('102').'<br>'; echo
intval(+102).'<br>'; echo
intval(-102).'<br>'; echo
intval(0102).'<br>'; echo
intval('0002').'<br>'; echo
intval(1e20).'<br>'; echo
intval(0x1B).'<br>';
echo intval(10200000).'<br>';
echo intval(10200000000000000000).'<br>';
echo intval(10, 2).'<br>';
echo intval('10', 2).'<br>';
?>
Output :
102
102
102
102
-102
66
2
0
27
10200000
0
10
2
print_r
The print_r() function is used to print human-readable information about a variable. Syntax:print_r(var_name,
return_output)
Parameter:
/Optional
var_name The variable being printed. Required String
Example -1:
<?php
$var1='abc';
$var2=123.33;
print_r($var1);
echo'<br>';
print_r($var2);
echo'<br>';
$abc =
array('Subj1'=>'Physics','Subj2'=>'Chemistry','Subj3'=>'Mathematics','Class'=>array(5,6,7,8));
print_r($abc);
?>
Copy
Output :
abc 123.33
Array ( [Subj1] => Physics [Subj2] => Chemistry [Subj3] => Mathematics [Class]
=> Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 ) )
Example -2 :
In the following example, the second parameter of the function has used, capture the output ofthe
function in a variable then print the output with echo.
<?php
$var1='abc';
$result = print_r($var1);
echo $result.'<br>';
$var2=123.33;
$result = print_r($var2);
echo $result.'<br>';
$abc =
array('Subj1'=>'Physics','Subj2'=>'Chemistry','Subj3'=>'Mathematics','Class'=>array(5,6,7,8));
$result = print_r($abc);
echo $result.'<br>';
?>
Output:
abc
123.33
Array ( [Subj1] => Physics [Subj2] => Chemistry [Subj3] => Mathematics [Class] => Array ( [0] => 5
[1] => 6 [2] => 7 [3] => 8 ) )
String Function
A string is a sequence of characters, like “Hello World”. PHP provides string functions toperforms
certain operations on String.
"\t" : tab
"\x0B" : vertical
tab"\r" : carriage
return
"\t" : tab
"\x0B" : vertical
tab"\r" : carriage
return
"\x0B" : vertical
tab"\r" : carriage
return
A negative number -
Start at a specified
position fromthe end of
the string
0 - Start at the
firstcharacter in
string
Possible values:
TRUE - Case-insensitive
Example:
<?php
echo chr(52) . "<br>"; // Decimal valueecho
chr(052) . "<br>"; // Octal value echo
chr(0x52) . "<br>"; // Hex value echo
ord("h")."<br>";
echo ord("hello")."<br>";
echo strtolower("Hello WORLD.")."<br>"; echo
strtoupper("Hello WORLD.")."<br>"; echo
strlen("Hello World")."<br>";
echo ltrim(" \n Hello World")."<br>"; echo
rtrim("Hello World \n ")."<br>"; echo
trim("Hello World")."<br>"; echo
substr("Hello world",6)."<br>"; echo
substr("Hello world",6,3)."<br>";
echo strcmp("Hello world!","Hello world!")."<br>";echo
strcmp("Hello world!","Hello!")."<br>";
echo strcasecmp("Hello world!","Hello WORLD!")."<br>";
$mystring = 'Hello PHP';
$findme = 'PHP';
$pos = strpos($mystring, $findme);if
($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";echo
"<br>";
echo " and exists at position $pos"."<br>";
}
echo strrpos("I love php, I love php too!","php")."<br>";echo
strstr("Hello world!","WORLD")."<br>";
echo stristr("Hello world!","WORLD")."<br>";
echo str_replace("world","Mummy","Hello world!")."<br>";
echo strrev("hello")."<br>";print
"Hello"."<br>";
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str))."<br>";
echo "Befor using implode() function: array('Hello','PHP','Javatpoint')"."<br>";
$arr = array('Hello','PHP','Javatpoint');
echo "After using 'implode()' function: ".implode(" ",$arr)."<br>";echo
join("",$arr)."<br>";
echo md5("bca")."<br>";
$str="Hello"; print_r(str_split($str,3))."<br>";
$str="Good morning";
echo "<br>".str_shuffle($str)."<br>";echo
strcspn($str,"m")."<br>";
echo strpbrk($str,"m")."<br>";
echo substr_compare("Hello world!","Hello world!",0)."<br>"; // the two strings are equal echo
substr_compare("Hello world!","Hello",0)."<br>"; // string1 is greater than string2 echo
substr_compare("Hello world!","Hello world! Hello!",0)."<br>"; // str1 is less than str2 echo
substr_count("Hello world. The world is nice","world")."<br>";
echo ucfirst("good morning")."<br>"; echo
ucwords("good morning")."<br>";
?>
Math Function
Function Description Syntax
Abs The abs() function number abs ( mixed $number )
returns absolute value of
given number. It returns
an integer value but if
you
pass floating point value,
itreturns a float value.
ceil The ceil() function float ceil ( float $value )
roundsfractions up.
floor The floor() function float floor ( float $value )
roundsfractions down.
round The round() function is float round($number, $precision, $mode);
used to find rounds a
floatnumber. It has
three parameters and
returns the
round value.
fmod fmod() function is float fmod ( float $x , float $y
mathematical function, );where $x specifies the
which is used to return divident
thefloating point $y specifies the divisor
remainder of
the division of the
argument.
min It returns the lowest min(array_values);
valuein an array, or the or
lowest value of several min(value1,value2,value3...);
specified
values.
max It is used to return the max(array_values);
highest value in an array, or
orthe highest value of max(value1,value2,value3,value4...);
several
specified values.
pow The pow() is a PHP number pow ( number $base , number $exp )
mathematic function.
It raises the first
number tothe power of
the second
number.
sqrt The sqrt() function float sqrt ( float $arg )
returnssquare root of
given argument.
rand The rand() function is int rand ( void
usedto generate random )or
integer. int rand ( int $min , int $max )
where, $min, Specifies the lowest number
toreturned.
$max, Specifies the highest number to returned.
cos() It is used to return the cos(number);
cosine of a number.
acos() It is used to return the arc acos(number);
cosine of a number.
sin() It is used to return the sine float sin ( float $arg )
of a number.
asin() It is used to find the arc asin($value)
sine of a number. Specify
anumber between -1 to 1
tan() It is used to return tan(number)
thetangent of a
number.
atan() It returns arc tangent of atan(arg);
argas a numeric value
between
Pi/2 and pi/2 radians.
bindec() The bindec() function number bindec ( string $binary_string )
converts binary
numberinto decimal.
decbin() The decbin() function string decbin ( int $number )
converts decimal
numberinto binary. It
returns
binary number as a string.
hexdec() This function converts hexdec(hexavalue)
hexadecimal to decimal.
dechex() The dechex() function string dechex ( int $number )
converts decimal number
into hexadecimal. It
returnshexadecimal
representation
of given number as a
string.
is_finite() To check whether a value Bool is_finite ( float $val );
is finite or not.
is_infinite() It is used to check whether bool is_infinite ( float $val );
a value is infinite or not.
log() It is used to return the log(number,base);
natural logarithm of where, base to use but default is 'e'
anumber.
base_convert() The base_convert() string base_convert ( string
function allows you to $number ,int $frombase , int
convert any base number $tobase )
toany base number. For
example, you can convert
hexadecimal number to
binary, hexadecimal to
octal, binary to octal,
octal to hexadecimal,
binary to
decimal etc.
deg2rad() It converts a degree float deg2rad ( float $number );
value to a radian value.
Example:
<?php
echo (abs(-7)."<br/>"); //7
echo (ceil(3.3)."<br/>"); //4
echo (floor(3.3)."<br/>"); //3
echo (sqrt(16)."<br/>"); //4 echo
(decbin(2)."<br/>");//10 echo
(dechex(10)."<br/>");//a echo
(bindec(10)."<br/>");// 2
$n1=10;
echo (base_convert($n1,10,2)."<br/>");// 1010
echo(round(1.6) ."<br/>");//2
$x = 7;
$y = 2;
echo(fmod($x,$y)."<br>");//1
echo min(4,14,3,5,14.2)."<br>";
echo max(4,14,3,5,14.2)."<br>";echo
pow (3, 2).'<br>';
echo rand()."<br>";
echo cos(3)."<br>";
echo acos(3)."<br>";
echo tan(3)."<br>";
echo atan(3)."<br>";
echo sin(1)."<br>";
echo asin(0)."<br>";
$nos=2;
echo "<br>"."By using 'is_finite()' Function :".is_finite($nos) ."<br>"; echo
"<br>"."By using 'is_infinite()' Function :".is_finite($nos) ."<br>";echo log(2)."<br>";
$degree=15;
echo "By using 'deg2rad()' function, your radian equivalent is :".deg2rad($degree);
?>
Date Function
PHP date function is an in-built function that simplify working with date data types. The PHPdate
function is used to format a date or time into a human readable format. It can be used to display the
date of article was published. record the last updated a data in a database.
Example:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l"). "<br>";
print_r(getdate()). "<br>";
var_dump(checkdate(12,31,-400)); echo
"<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
echo "<br>";
$t=time(); echo($t .
"<br>");
echo(date("Y-m-d",$t));
echo "Oct 3, 1975 was on a ".date("l", mktime(0,0,0,10,3,1975));echo "<br>";
$date=date_create("2013-03-15");
date_add($date,date_interval_create_from_date_string("40 days")); echo
date_format($date,"Y-m-d");
echo "<br>";
$date=date_create("2013-03-15 23:40:00",timezone_open("Europe/Oslo")); echo
date_format($date,"Y/m/d H:iP");
echo "<br>";
echo(strftime("%B %d %Y, %X %Z",mktime(20,0,0,12,31,98))."<br>");setlocale(LC_ALL,"hu_HU.UTF8");
echo(strftime("%Y. %B %d. %A. %X %Z"));echo
“<br>”;
echo(strtotime("now") . "<br>");
echo(strtotime("3 October 2005") . "<br>");
echo(strtotime("+5 hours") . "<br>");
echo(strtotime("+1 week") . "<br>");
echo(strtotime("+1 week 3 days 7 hours 5 seconds") . "<br>");echo(strtotime("next
Monday") . "<br>");
echo(strtotime("last Sunday"));
echo “<br>”;
print_r(gettimeofday());
echo “<br>”;
echo gettimeofday(true);
?>
Array Function
$cars=array("Volvo","BMW","Toyota");
$my_array = array("Dog","Cat","Horse");
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); asort($age);
arsort($age);
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota"); print_r(array_reverse($a));
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2); print_r($result);
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow"); print_r(array_merge_recursive($a1,$a2));
$a=array("a"=>"red","b"=>"green","c"=>"blue"); echo
array_shift($a);
print_r ($a);
$a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,2));
$a=array("a"=>"red","b"=>"green","c"=>"red"); print_r(array_unique($a));
$a=array("a"=>"red","b"=>"green");
array_unshift($a,"blue"); print_r($a);
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r(array_keys($a));
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
$a=array("red","green");
array_push($a,"blue","yellow"); print_r($a);
$a=array("red","green","blue");
array_pop($a);
print_r($a);
$a=array("Dog","Cat","Horse","Bear","Zebra"); array_multisort($a);
print_r($a);
$a=array("a"=>"red","b"=>"green","c"=>"blue"); echo
array_search("red",$a);
?>
Miscellaneous Function
Function Description Syntax
define The define() function defines a constant. define(name,value,case_insensitive
Constants are much like variables, except )
forthe following differences:
A constant's value cannot be
changedafter it is set
Constant names do not need a
leadingdollar sign ($)
Constants can be accessed regardless
ofscope
Constant values can only be strings
and
numbers
constant returns the value of a constant. constant(constant)
include Used to insert the content of one PHP file into include ‘filename’
another PHP file (before the server executes
it). On failure, It will only produce a
warningand the script will continue
require Used to insert the content of one PHP file into require ‘filename’
another PHP file (before the server executes
it). On failure, it will produce a fatal error
andstop the script.
Header Sends a raw HTTP header to a client. It Header(string, replace,
shouldbe a first line. http_response_code)
Header(‘Location:P
http://www.tnrao.com/’);
Die prints a message and exits the current script die(message)
exit prints a message and exits the current script. exit(message)
$site = "https://www.w3schools.com/";
$site = "https://www.w3schools.com/";
Example:
<?php
$file = fopen("test.txt","r");
$file = fopen("/home/test/test.txt","r");
$file = fopen("/home/test/test.gif","wb");
$file = fopen("http://www.example.com/","r");
$file = fopen("ftp://user:[email protected]/test.txt","w");
?>
Example:
<?php
$file = fopen("test.txt","r");
fread($file,"10"); fclose($file);
?>
Example:
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");fclose($file);
?>
Example:
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only modefwrite($fp,
'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);
fclose($file);
?>
Example:
<?php
echo file_exists("test.txt");
?>
Example:
<?php
$file = "test.txt";
if(is_readable($file))
{
echo ("$file is readable");
}
else
{
echo ("$file is not readable");
}
?>
Example:
<?php
$file = "test.txt";
if(is_writable($file))
{
echo ("$file is writeable");
}
else
{
echo ("$file is not writeable");
}
?>
Example:
<?php
$file = fopen("test.txt","r");echo
fgets($file); fclose($file);
?>
Example:
<?php
$file = fopen("test2.txt","r");echo
fgetc($file);
fclose($file);
?>
Example:
<?php print_r(file("test.txt"));
?>
Example:
<?php
echo file_get_contents("test.txt");
?>
Example:
<?php
$list = array(
"Peter,Griffin,Oslo,Norway",
"Glenn,Quagmire,Oslo,Norway",
);
$file = fopen("contacts.csv","w");foreach
($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file);
?>
Example:
<?php
$file = fopen("test.txt","w");
echo fputs($file,"Hello World. Testing!");
fclose($file);
?>
Example:
<?php
echo file_put_contents("test.txt","Hello World. Testing!");
?>
Example:
<?php
$file = fopen("test.txt","r");
fclose($file);
?>
Example:
<?php
$file = fopen("test.txt","r");
// read first line
fgets($file);
// move back to beginning of file
fseek($file,0);
?>
Example:
<?php
$file = fopen("test.txt","r");
fclose($file);
?>
Example:
<?php
echo copy("source.txt","target.txt");
?>
Example:
<?php
$file = "test.txt";if
(!unlink($file))
{
echo ("Error deleting $file");
}
else
{
echo ("Deleted $file");
}
?>
Example:
<?php
rename("images","pictures");
?>