0% found this document useful (0 votes)
2 views

Unit 1_Web

The document outlines the curriculum for a Web Programming course using PHP at T. N. Rao College of Information Technology, covering topics such as PHP basics, configuration, variables, functions, and error reporting. It emphasizes the features and advantages of PHP, its applications in web development, and prerequisites for learning PHP. Additionally, it provides instructions for installing and running PHP on XAMPP, along with examples of PHP syntax and variable handling.

Uploaded by

jatinchauhan6560
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit 1_Web

The document outlines the curriculum for a Web Programming course using PHP at T. N. Rao College of Information Technology, covering topics such as PHP basics, configuration, variables, functions, and error reporting. It emphasizes the features and advantages of PHP, its applications in web development, and prerequisites for learning PHP. Additionally, it provides instructions for installing and running PHP on XAMPP, along with examples of PHP syntax and variable handling.

Uploaded by

jatinchauhan6560
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 143

T. N.

Rao College of Information Technology,Rajkot


Class: BCA Semester – II
CS-08: WEB PROGRAMMIN
Academic Year – 2022–2023

CS-08: Web Programming (PHP)


B.C.A. Semester - 2
Topic-1
PHP Basic

□ 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?

 PHP is a server-side scripting language that is used for web development.


 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language(free to download and use).
 PHP was created by Rasmus Lerdirf in 1994 but appeared in the market in 1995.

Why PHP?

 PHP can be installed on any OS(Windows, Linux,Unix,Mac OS X etc)


 PHP can be installed on any webserver(Apache, IIS, Netscape etc)
 PHP supports a wide range of databases(MySQL,Informix, Oracle, Sybase, ODBC etc.)
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side
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 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

Where We use PHP?

 For Server side scripting


o Dynamic web pages
 For Building Client side GUI Application
o Desktop Application
 For Command Line Scripting
o Task scheduler on windows, text processing tasks etc.

There are some important features of PHP given below:

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.

Familiarity with syntax:


PHP has easily understandable syntax. Programmers are comfortable coding with it.

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.

Loosely Typed Language:

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.

Web servers Support:

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.

A Helpful PHP Community:

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.

HTML - HTML is used to design static webpage.


CSS - CSS helps to make the webpage content more effective and attractive.
JavaScript - JavaScript is used to design an interactive website.

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.

How to install XAMPP server on windows


We will learn how to install the XAMPP server on windows platform step by step. Follow
the below steps and install the XAMPP server on your system.

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 5: Click Next and move ahead.


Step 6: XAMPP is ready to install, so click on the Next button and install the XAMPP.

Step 7: A finish window will display after successful installation. Click on the Finish button.

Step 8: Choose your preferred language.

Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run the php program on
the localhost.

How to run PHP programs on XAMPP, see in the next tutorial.


Step 10: If no error is shown, then XAMPP is running successfully.

How to run PHP code in XAMPP

● 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.

Step 1: Create a simple PHP program like hello world.


It starts with <?php and ends with ?>.
The syntax of PHP tag is given below:

<?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).

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:
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.

 Understanding of PHP.INI file

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.

The syntax of PHP echo is given below:

void echo ( string $arg1 [, string $... ] )

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.

echo is faster than the print statement.


PHP echo: printing string

File: echo1.php

Input output
<?php Hello by PHP echo
echo "Hello by PHP echo"; PHP echo: printing multi line string

echo "Hello escape \"sequence\" characters"; Hello escape "sequence" characters

$msg="Hello JavaTpoint PHP"; Message is: Hello JavaTpoint PHP


echo "Message is: $msg";
?>

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.

Syntax of declaring a variable in PHP is given below:

$variablename=value;

Rules for declaring PHP variable:

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.

PHP Variable: Declaring string, integer, and float

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/>";
?>

PHP Variable: Sum of two variables

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. ?>

PHP Variable: Rules

PHP variables must start with letter or underscore only.

PHP variable can't be start with numbers and special symbols.

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
?>

PHP Variable Scope (Static & global variable)

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."

PHP has three types of variable scopes:

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.

Let's understand the global variables with the help of an example:

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();
?>

Using $GLOBALS instead of global

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.

PHP Single Line Comments


There are two ways to use single line comments in PHP.
o // (C++ style single line comment)
o # (Unix Shell style single line comment)

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. ?>

PHP Multi Line Comments

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";
?>

GET & POST method


There are two ways the browser client can send information to the web server.

 The GET Method


 The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In
this scheme, name/value pairs are joined with equal signs and different pairs are separated by
the ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other nonalphanumeric
characters are replaced with a hexadecimal values. After the information is encoded it is sent to
the server.

The GET Method


The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
 The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
 The GET method is restricted to send upto 1024 characters only.
 Never use GET method if you have password or other sensitive information to be sent to
the server.
 GET can't be used to send binary data, like images or word documents, to the server.
 The data sent by GET method can be accessed using QUERY_STRING environment
variable.
 The PHP provides $_GET associative array to access all the sent information using GET
method.

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>

<form action = "<?php $_PHP_SELF ?>" method = "GET">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
It will produce the following result −

The POST Method


The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
 The POST method does not have any restriction on data size to be sent.
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
 The PHP provides $_POST associative array to access all the sent information using POST
method.
Try out following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";

exit();
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
It will produce the following result −

The $_REQUEST variable

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>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</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:

$num=10+20;//+ is the operator and 10,20 are operands

In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.

PHP Operators can be categorized in following forms:


o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators

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.

Operator Name Example Explanation

+ Addition $a + $b Sum of operands

- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands

% Modulus $a % $b Remainder of operands

** Exponentiation $a ** $b $a raised to the power $b

The exponentiation (**) operator has been introduced in PHP 5.6.

Assignment Operators

The assignment operators are used to assign value to different variables. The basic assignment
operator is "=".
Operator Name Example Explanation

= Assign $a = $b The value of right operand is assigned to the left operand.

+= Add then Assign $a += $b Addition same as $a = $a + $b

-= Subtract then Assign $a -= $b Subtraction same as $a = $a - $b

*= Multiply then Assign $a *= $b Multiplication same as $a = $a * $b

/= Divide then Assign $a /= $b Find quotient same as $a = $a / $b


(quotient)

%= Divide then Assign $a %= $b Find remainder same as $a = $a % $b


(remainder)

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.

Operator Name Example Explanation

& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.

| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1

^ Xor (Exclusive or) $a ^ $b Bits that are 1 in either $a or $b are set to 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:

Operator Name Example Explanation

== Equal $a == $b Return TRUE if $a is equal to $b

=== 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

!= Not equal $a != $b Return TRUE if $a is not equal to $b

<> Not equal $a <> $b Return TRUE if $a is not equal to $b

< Less than $a < $b Return TRUE if $a is less than $b

> Greater than $a > $b Return TRUE if $a is greater than $b

<= 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

<=> Spaceship $a <=>$b Return -1 if $a is less than $b


Return 0 if $a is equal $b
Return 1 if $a is greater than $b

Incrementing/Decrementing Operators

The increment and decrement operators are used to increase and decrease the value of a
variable.

Operator Name Example Explanation

++ Increment ++$a Increment the value of $a by one, then return $a

$a++ Return $a, then increment the value of $a by one

-- Decrement --$a Decrement the value of $a by one, then return $a


$a-- Return $a, then decrement the value of $a by one

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.

Operator Name Example Explanation

And And $a and $b Return TRUE if both $a and $b are true

Or Or $a or $b Return TRUE if either $a or $b is true

Xor Xor $a xor $b Return TRUE if either $ or $b is true but not both

! Not ! $a Return TRUE if $a is not true

&& And $a && $b Return TRUE if either $a and $b are true

|| Or $a || $b Return TRUE if either $a or $b is true

String Operators

The string operators are used to perform the operation on strings. There are two string
operators in PHP, which are given below:

Operator Name Example Explanation

. Concatenation $a . $b Concatenate both $a and $b

.= 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

+ Union $a + $y Union of $a and $b

== Equality $a == $b Return TRUE if $a and $b have same key/value pair

!= Inequality $a != $b Return TRUE if $a is not equal to $b

=== Identity $a === $b Return TRUE if $a and $b have same key/value pair of same type in
same order

!== Non- $a !== $b Return TRUE if $a is not identical to $b


Identity

<> Inequality $a <> $b Return TRUE if $a is not equal to $b

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();

//testing the type of object


if( $charu instanceof Developer)
{
echo "Charu is a developer.";
}
else
{
echo "Charu is a programmer.";
}
echo "</br>";
var_dump($charu instanceof Developer); //It wi
ll return true.
var_dump($charu instanceof Programmer); //It wi
ll return false.
?>

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.

Operator Name Example Explanation

`` backticks echo `dir`; Execute the shell command and return the result.
Here, it will show the directories available in current folder.

Note: Note that backticks (``) are not single-quotes.

Error Control Operators


PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an expression,
any error message will be ignored that might be generated by that expression.

Operator Name Example Explanation

@ At @file ('non_existent_file') Intentional file error

PHP Operators Precedence


Let's see the precedence of PHP operators with associativity.

Operators Additional Information Associativity

clone new clone and new non-associative

[ array() left

** arithmetic right

++ -- ~ (int) (float) (string) (array) (object) (bool) @ increment/decrement and types right
Instanceof types non-associative

! logical (negation) right

*/% arithmetic left

+-. arithmetic and string concatenation left

<< >> bitwise (shift) left

< <= > >= comparison non-associative

== != === !== <> comparison non-associative

& bitwise AND left

^ bitwise XOR left

| bitwise OR left

&& logical AND left

|| logical OR left

?: ternary left

= += -= *= **= /= .= %= &= |= ^= <<= >>= => assignment right

And logical left

Xor logical left

Or logical left

, many uses (comma)

Conditional Structure & Looping Structure


PHP If Else

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

PHP if statement allows conditional execution of code. It is executed if condition is true.

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";
}
?>

PHP If-else Statement

PHP if-else statement is executed whether condition is true or false.


If-else statement is slightly different from if statement. It executes one block of code if the
specified condition is true and another block of code if the condition is false.

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. }
?>

PHP If-else-if Statement

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";
}
?>

PHP nested if Statement

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;
}

Important points to be noticed about switch case:


1. The default is an optional statement. Even it is not important, that default must always be the last
statement.
2. There can be only one default in a switch statement. More than one default may lead to
a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of statement.
4. The break statement is optional to use in switch. If break is not used, all the statements will
execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and less
readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.
PHP Switch Flowchart

PHP Switch Example


Input Output
number is equal to 20
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
PHP switch statement with character

Program to check Vowel and consonant

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 switch statement with String

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

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";
}
?>

PHP nested switch statement

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;
}
?>

PHP For Loop


PHP for loop can be used to traverse set of code for the specified number of times.

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.

Increment/decrement - It increments or decrements the value of the variable.

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++);
?>

PHP Nested For Loop


We can use for loop inside for loop in PHP, it is known as nested for loop. The inner for loop
executes only when the outer for loop condition is found true.

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.

In foreach loop, we don't need to increment the value.

Syntax

foreach( $array as $var ){


//code to be executed
}
?>

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.

It should be used if the number of iterations is not known.

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;

PHP While Loop Flowchart

PHP While Loop Example


Input output
1
<?php 2
3
$n=1; 4
while($n<=10){ 5
6
echo "$n<br/>"; 7
$n++; 8
9
} 10
?>

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. ?>

PHP Nested While Loop

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++;
}
?>

PHP Infinite While Loop

If we pass TRUE in while loop, it will be an infinite loop.

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!

PHP do-while loop


PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while
loop is guaranteed to run at least once.

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;

?>

Difference between while and do-while loop


while Loop do-while loop

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

PHP Break: inside loop

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;
}
}
?>

PHP Break: inside inner loop

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;
}
}
}
?>

PHP Break: inside switch statement

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");
}
?>

PHP Break: with array of string


Input output
One
<?php Two
//declare an array of string Three

$number = array ("One", "Two", "Three", "Stop", "Four");


foreach ($number as $element) {
if ($element == "Stop") {
break;
}
echo "$element </br>";
}
?>

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.

PHP Break: switch statement without break

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';
}
?>

PHP Break: using optional argument

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.

PHP continue statement


The PHP continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition.

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:

PHP Continue Example with for loop

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

for ($i =1; $i<=3; $i++) {


//inner loop
for ($j=1; $j<=3; $j++) {
if (!($i == $j) ) {
continue; //skip when i and j does not have same values
}
echo $i.$j;
echo "</br>";
}
}
?>
PHP continue Example in while loop

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++;
}
?>

PHP continue Example with array of string

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>";
}
?>

PHP continue Example with optional argument

The continue statement accepts an optional numeric value, which is used accordingly. The
numeric value describes how many nested structures it will exit.

Example

Look at the below example to understand it better:

Input output
12
<?php 13
//outer loop 21
23
for ($i =1; $i<=3; $i++) { 31
//inner loop 32

for ($j=1; $j<=3; $j++) {


if (($i == $j) ) { //skip when i and j have same values
continue 1; //exit only from inner for loop
}
echo $i.$j;
echo "</br>";
}
}

?>
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.

Advantage of PHP Array

Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types

There are 3 types of array in PHP.

1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed 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 Indexed Array Example


File: array1.php
Input Output
Size: Big, Medium and Short
<?php
$size=array("Big","Medium","Short");
echo "Size: $size[0], $size[1] and $size[2]";
?>
File: array2.php
Input Output
Size: Big, Medium and Short

<?php
$size[0]="Big";
$size[1]="Medium";
$size[2]="Short";
echo "Size: $size[0], $size[1] and $size[2]";
?>

Traversing PHP Indexed Array

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. ?>

Count Length of PHP Indexed Array


PHP provides count() function which returns length of an array.

Input Output
3
1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>

PHP Associative Array


PHP allows you to associate name/label with each array elements in PHP using => symbol. Such
way, you can easily remember the element because each element is represented by label than an
incremented number.

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/>";
?>

Traversing PHP Associative Array


By the help of PHP for each loop, we can easily traverse the elements of PHP associative array.

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)
);

PHP Multidimensional Array Example


Let's see a simple example of PHP multidimensional array to display following tabular data. In
this example, we are displaying 3 rows and 3 columns.

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.

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.

Easy to understand: PHP functions separate the programming logic. So it is easier to


understand the flow of the application because every logic is divided in the form of functions.

PHP User-defined Functions


We can declare and call user-defined functions easily. Let's see the syntax to declare user-
defined functions.

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.

PHP Functions Example


File: function1.php
1. <?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>
Output:

Hello PHP Function

PHP Function Arguments


We can pass the information in PHP function through arguments which is separated by comma.

PHP supports Call by Value (default), Call by Reference, Default argument


values and Variable-length argument list.

Let's see the example to pass single argument in PHP function.

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

Let's see the example to pass two argument in PHP function.

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:

Hello Sonoo, you are 27 years old


Hello Vimal, you are 29 years old
Hello John, you are 23 years old

PHP Call By Reference

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.

Let's see a simple example of call by reference in PHP.

File: functionref.php
Input Output
Hello Call By Reference
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>

PHP Function: Default Argument Value


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.

File: functiondefaultarg.php
Input output
Hello Rajesh
<?php Hello Sonoo
function sayHello($name="Sonoo"){ Hello John

echo "Hello $name<br/>";


}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>

PHP Function: Returning Value

Let's see an example of PHP function that returns value.

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 Function

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.

PHP Parameterized Example 1

Addition and Subtraction

In this example, we have passed two parameters $x and $y inside two


functions add() and sub().

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);

//Subtracting two numbers


function sub($x, $y) {
$diff = $x - $y;
echo "Difference between two numbers is = $diff";
}
sub(943, 467);
?>
</body>
</html>

PHP Parameterized Example 2

Addition and Subtraction with Dynamic number

In this example, we have passed two parameters $x and $y inside two


functions add() and sub().

<?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:

We passed the following number,


Now clicking on ADDITION button, we get the following output.

Now clicking on SUBTRACTION button, we get the following output.

PHP Call By Value

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.

Let's understand the concept of call by value by the help of examples.

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.

Let's understand the concept of call by reference by the help of examples.


Example 1
In this example, variable $str is passed to the adder function where it is concatenated with 'Call
By Reference' string. Here, printing $str variable results 'This is Call By Reference'. It is because
changes are done in the actual variable $str.

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

3. echo "Hello $name<br/>";


4. }
5. sayHello("Sonoo");
6. sayHello();//passing no value
7. sayHello("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

echo "Greeting: $first $last<br/>";


}
greeting();
greeting("Rahul");
greeting("Michael","Clark");
?>
Example 3
Input Output
Addition is: 20
<?php Addition is: 30
function add($n1=10,$n2=10){ Addition is: 80

$n3=$n1+$n2;
echo "Addition is: $n3<br/>";
}
add();
add(20);
add(40,40);
?>

PHP Variable Length Argument Function

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.

Let's see a simple example of PHP variable length argument function.

INPUT OUTPUT
10
<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}

echo add(1, 2, 3, 4);


?>
func_num_args
func_num_args — Returns the number of arguments passed to the function
Description
int func_num_args ( void )
Gets the number of arguments passed to the function.
This function may be used in conjunction with func_get_arg() and func_get_args() to allow user-
defined functions to accept variable-length argument lists.
Example:
INPUT OUTPUT
<?php Number of arguments: 3
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs\n";
}
foo(1, 2, 3);
?>
func_get_arg
func_get_arg — Return an item from the argument list

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);
?>

Example 2 : Factorial Number


Input Output
120
<?php
function factorial($n)
{
if ($n < 0)
return -1; /*Wrong value*/
if ($n == 0)
return 1; /*Terminating condition*/
return ($n * factorial ($n -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:

Name Description Required / Type


Optional

var_name The name of the variable. Required Mixed*


*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.Return

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:

Name Description Required Type

/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*

Variable2 More variable to be checked. Optional 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

var1 The variable to be unset. Required Mixed*

var2 Another variable to be unset Optional Mixed*

echo 'Before using unset() the value of $xys is : '. $xyz.'<br>';

Before using unset() the value of $xys is : w3resource.com

Name Description Required Type

/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:

Name Description Required / Type


Optional

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:

Name Description Required / Type


Optional

var_name The scalar value being converted to an integer Required Mixed*

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:

Name Description Required Type

/Optional
var_name The variable being printed. Required String

return_outpu To capture the output in a variable, the Optional Boolean


t parametershould set TRUE. The default value is
FALSE.
Return value:
If the variable is an integer or a float or a string the function returns value of the variable. If the variable is
an array the function returns keys and elements, a similarly notation is used for the object. Setting TRUE
to return_output parameter the function returns a 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.

Function Description Syntax

chr() Returns a character string chr ( int $bytevalue );


from a specified ASCII
value. The ASCII value
can be specified in
decimal, octal, or hex
values. Octal values
are defined by a
leading 0, while hex
values are
defined by a leading 0x.

ord() It is used to return int ord ( string $string );


ASCII value of the first
character of a string.
strtolower() Converts a string string strtolower ( string $string )
tolowercase
letters
strtoupper() Converts a string string strtoupper ( string $string )
touppercase
letters
strlen() It is used to return int strlen ( string $string )
thelength of a string.

ltrim() It is used to remove ltrim(string,charlist);


whitespace from the where charlist:
leftside of a string. "\0" : NULL

"\t" : tab

"\n" : new line

"\x0B" : vertical

tab"\r" : carriage

return

" " : ordinary white space


rtrim() It is used to remove rtrim(string,charlist);
whitespace from the
right side of a string. where charlist:
"\0" : NULL

"\t" : tab

"\n" : new line

"\x0B" : vertical

tab"\r" : carriage

return

" " : ordinary white space


trim() It is used to strip trim(string,charlist);
whitespace from the where charlist:
beginning and end of
a
string or both side of "\0" : NULL
astring.
"\t" : tab

"\n" : new line

"\x0B" : vertical

tab"\r" : carriage

return

" " : ordinary white space


substr() Returns a part of substr(string,start,length)
astring
Parameter Description

string Required. Specifies


thestring to return a
part of

start Required. Specifies


whereto start in the
string

A positive number - Start


ata specified position in
the string

A negative number -
Start at a specified
position fromthe end of
the string

0 - Start at the
firstcharacter in
string

length Optional. Specifies the


length of the returned
string. Default is to the
endof the string.

A positive number - The


length to be returned
fromthe start parameter
Negative number - The
length to be returned fromthe
end of the string

strcmp() Compares two strings(case- strcmp(string1,string2)


sensitive)

strcasecmp() Compares two strings(case- strcasecmp(string1,string2)


insensitive)
strpos() It is used to return the
position of the first strpos(string,find,start)
occurrence of a string
inside another string. Parameter Description
strpos(string,find,start);

string Required. Specifies the string to


search

find Required. Specifies the string to


find

start Optional. Specifies where to


begin the search

strrpos() It is used to find the strpos(string,find,start)


position of the last
occurrence of a substring in
a string. This function is
Parameter Description
case- sensitive.

string Required. Specifies the string to


search

find Required. Specifies the string to


find
start Optional. Specifies where to
beginthe search

strstr() Finds the first strstr(string,search,before_search);


occurrence of a string
inside another string Paramete Description
(case-sensitive) r

string Required. Specifies the string


tosearch

search Required. Specifies the string to


search for. If this parameter is a
number, it will search for the
character matching the ASCII
valueof the number

before_se Optional. A boolean value


arch whose default is "false". If set to
"true", itreturns the part of the
string beforethe first occurrence
of
the search parameter.

stristr() Finds the first stristr(string,search,before_search)


occurrence of a string
inside another string Parameter Description
(case-insensitive)

string Required. Specifies the string


tosearch

search Required. Specifies the string


tosearch for. If this parameter
is a number, it will search for
the
character matching the ASCII
value of the number

before_sear Optional. A boolean value


ch whosedefault is "false". If set
to "true",it returns the part of
the string before the first
occurrence of
the search parameter.

str_replace() Replaces a part of a str_replace(find,replace,string,count)


string with another
string Parameter Description

find Required. Specifies the value


tofind

replace Required. Specifies the value


toreplace the value in find

string Required. Specifies the string


tobe searched

count Optional. A variable that


countsthe number of
replacements

strrev() Reverses a string strrev(string)

echo() It is used for output echo(strings)


oneor more strings.

print() Outputs one or more print(strings)


strings

explode() It is used to break a explode(separator,string,limit)


string into an array.
Paramet Description
er

separato Required. Specifies where to break


r the string

string Required. The string to split

limit Optional. Specifies the number


ofarray elements to return.

Possible values:

 Greater than 0 - Returns


anarray with a maximum
of limit element(s)
 Less than 0 - Returns
an array except for the
last -limit elements()
 0 - Returns an array with
oneelement

Implode() It is used to return a implode(separator,array)


string from the
elementsof an array. Paramete Description
r

separator Optional. Specifies what to put


between the array elements.
Defaultis "" (an empty string)

array Required. The array to join to


astring

Join() It is the Alias of join(separator,array)


implode() function.
Paramet Description
er

separator Optional. Specifies what to put


between the array elements.
Defaultis "" (an empty string)

array Required. The array to join to


astring

md5() It is used to calculate md5(string,raw)


the MD5 hash of a where, raw is Optional. Specifies hex or
string. binaryoutput format:

 TRUE - Raw 16 character binary format


 FALSE - Default. 32 character hex number

str_split() It is used to split a str_split(string,length)


stringinto an array.

str_shuffle() It is used to randomly str_shuffle(string)


shuffle all characters
in a string.

strcspn() It returns the number strcspn(string,char,start,length)


of characters
(including
whitespaces) found in
a string before any
part of the specified
characters are found.
strpbrk() It is used to search a strpbrk(string,charlist)
string for any of a set
ofcharacters.
substr_compare( Compares two strings substr_compare(string1,string2,startpos,length,case
) from a specified start )
position (binary safe Paramet Description
and optionally case-
sensitive)
er

string1 Required. Specifies the first string


tocompare

string2 Required. Specifies the second


stringto compare

startpos Required. Specifies where to


start comparing in string1. If
negative, itstarts counting from
the end of the string

length Optional. Specifies how much


ofstring1 to compare

case Optional. A boolean value that


specifies whether or not to
perform acase-sensitive compare:

FALSE - Default. Case-sensitive

TRUE - Case-insensitive

substr_count() Counts the number of substr_count(string,substring,start,length)


times a substring Paramet Description
occursin a string
er

string Required. Specifies the string


tocheck

substrin Required. Specifies the string


g tosearch for

start Optional. Specifies where in string


tostart searching
length Optional. Specifies the length of
thesearch

ucfirst() Convert the firs string ucfirst ( string $str )


character of t
uppercas wor to
e d
ucwords() converts the first string ucwords ( string $str )
character of each
word in a string to
uppercase

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.

Function Description Syntax


date() The date() function date(format,timestamp);
formats a local date where,
andtime, and returns format:
the formatted date Required. Specifies the format of the outputted
string. datestring. The following characters can be
used:
 d - The day of the month (from 01 to 31)
 D - A textual representation of a day
(threeletters)
 j - The day of the month without
leadingzeros (1 to 31)
 l (lowercase 'L') - A full
textualrepresentation of a
day
 N - The ISO-8601 numeric representation
ofa day (1 for Monday, 7 for Sunday)
 S - The English ordinal suffix for the day
ofthe month (2 characters st, nd, rd or
th. Works well with j)
 w - A numeric representation of the day
(0for Sunday, 6 for Saturday)
 z - The day of the year (from 0 through
365)
 W - The ISO-8601 week number of
year(weeks starting on Monday)
 F - A full textual representation of a month
(January through December)
 m - A numeric representation of a
month(from 01 to 12)
 M - A short textual representation
of amonth (three letters)
 n - A numeric representation of a
month,without leading zeros (1 to 12)
 t - The number of days in the given month
 L - Whether it's a leap year (1 if it is a
leapyear, 0 otherwise)
 o - The ISO-8601 year number
 Y - A four digit representation of a year
 y - A two digit representation of a year
 a - Lowercase am or pm
 A - Uppercase AM or PM
 B - Swatch Internet time (000 to 999)
 g - 12-hour format of an hour (1 to 12)
 G - 24-hour format of an hour (0 to 23)
 h - 12-hour format of an hour (01 to 12)
 H - 24-hour format of an hour (00 to 23)
 i - Minutes with leading zeros (00 to 59)
 s - Seconds, with leading zeros (00 to 59)
 u - Microseconds (added in PHP 5.2.2)
 e - The timezone identifier
(Examples:UTC, GMT,
Atlantic/Azores)
 I (capital i) - Whether the date is
in daylights savings time (1 if
DaylightSavings Time, 0
otherwise)
 O - Difference to Greenwich time (GMT)
inhours (Example: +0100)
 P - Difference to Greenwich time (GMT)
inhours:minutes (added in PHP 5.1.3)
 T - Timezone abbreviations
(Examples:EST, MDT)
 Z - Timezone offset in seconds. The
offsetfor timezones west of UTC is
negative (- 43200 to 50400)
 c - The ISO-8601 date (e.g. 2013-
05-05T16:34:42+00:00)
 r - The RFC 2822 formatted date (e.g.
Fri,12 Apr 2013 12:01:05 +0200)
 U - The seconds since the Unix
Epoch(January 1 1970 00:00:00
GMT)
and the following predefined constants can also
be
used (available since PHP 5.1.0):
 DATE_ATOM - Atom (example: 2013-04-
12T15:52:01+00:00)
 DATE_COOKIE - HTTP Cookies
(example: Friday, 12-Apr-13
15:52:01UTC)
 DATE_ISO8601 - ISO-8601 (example:
2013-04-12T15:52:01+0000)
 DATE_RFC822 - RFC 822 (example: Fri,
12 Apr 13 15:52:01 +0000)
 DATE_RFC850 - RFC 850 (example:
Friday, 12-Apr-13 15:52:01 UTC)
 DATE_RFC1036 - RFC 1036 (example:
Fri, 12 Apr 13 15:52:01 +0000)
 DATE_RFC1123 - RFC 1123 (example:
Fri, 12 Apr 2013 15:52:01 +0000)
 DATE_RFC2822 - RFC 2822 (Fri, 12 Apr
2013 15:52:01 +0000)
 DATE_RFC3339 - Same as DATE_ATOM
(since PHP 5.1.3)
 DATE_RSS - RSS (Fri, 12 Aug 2013
15:52:01 +0000)
 DATE_W3C - World Wide Web
Consortium (example: 2013-
04- 12T15:52:01+00:00)
Where, timestamp is Optional. Specifies an
integerUnix timestamp. Default is the current
local time
(time())
getdate Returns date/time getdate(timestamp);
information of a
timestamp or the
current
local date/time
setdate Resets the current date setDate(year, month,day)
ofthe DateTime object
to a
different data.
checkdate The checkdate() function checkdate(month,day,year);
is used to validate
aGregorian date.
time The time() function time();
returns the current
time in the number of
secondssince the Unix
Epoch (January 1 1970
00:00:00
GMT).

mktime It returns the Unix mktime(hour,minute,second,month,day,year,is_dst


timestamp for a date. );
Paramete Description
r

hour Optional. Specifies the hour

minute Optional. Specifies the minute

second Optional. Specifies the second

month Optional. Specifies the month

day Optional. Specifies the day

year Optional. Specifies the year

is_dst Optional. Set this parameter to


1 if the time is during daylight
savings time (DST), 0 if it is
not,or -1 (the default) if it is
unknown. If it's unknown, PHP
tries to find out itself (which
maycause unexpected
results). Note: This parameter
became deprecated in PHP
5.1.0.The new timezone
handling features should be
used instead
date_add() Adds days, months, date_add(object,interval);
years, hours, where, object Specifies a DateTime object returned
minutes,and by date_create()
seconds to a date interval Specifies a DateInterval object
date_create() The date_create() date_create(time,timezone);
function returns a where time: Specifies a date/time string. NULL
newDateTime indicates the current time
object. timezone: Specifies the timezone of time. Default
isthe current timezone.
date_format() Returns a date date_format(object,format);
formattedaccording to where object: specifies a DateTime object
a specified returnedby date_create()
format
format: specifies format
gmdate() Formats a gmdate(format,timestamp);
GMT/UTCdate and echo gmdate("l") . "<br>";
time echo gmdate("l jS \of F Y h:i:s A");
localtime() Returns the local time localtime(timestamp,is_assoc);
where is_assoc
Optional. Specifies whether to return an
associativeor indexed array. FALSE = the array
returned is anindexed array. TRUE = the array
returned is an associative array. FALSE is
default.
The keys of the associative array are:
 [tm_sec] - seconds
 [tm_min] - minutes
 [tm_hour] - hour
 [tm_mday] - day of the month
 [tm_mon] - month of the year (January=0)
 [tm_year] - Years since 1900
 [tm_wday] - Day of the week (Sunday=0)
 [tm_yday] - Day of the year
 [tm_isdst] - Is daylight savings time
ineffect
strftime() Formats a local time strftime(format,timestamp);
and/or date according where, format specifies:
tolocale settings Required. Specifies how to return the result:
 %a - abbreviated weekday name
 %A - full weekday name
 %b - abbreviated month name
 %B - full month name
 %c - preferred date and time
representation
 %C - century number (the year divided
by100, range 00 to 99)
 %d - day of the month (01 to 31)
 %D - same as %m/%d/%y
 %e - day of the month (1 to 31)
 %g - like %G, but without the century
 %G - 4-digit year corresponding to the
ISOweek number (see %V).
 %h - same as %b
 %H - hour, using a 24-hour clock (00 to
23)
 %I - hour, using a 12-hour clock (01 to 12)
 %j - day of the year (001 to 366)
 %m - month (01 to 12)
 %M - minute
 %n - newline character
 %p - either am or pm according to the
given
time value
 %r - time in a.m. and p.m. notation
 %R - time in 24 hour notation
 %S - second
 %t - tab character
 %T - current time, equal to %H:%M:%S
 %u - weekday as a number (1 to
7),Monday=1. Warning: In Sun
SolarisSunday=1
 %U - week number of the current year,
starting with the first Sunday as the first
dayof the first week
 %V - The ISO 8601 week number of the
current year (01 to 53), where week 1 is
thefirst week that has at least 4 days in
the current year, and with Monday as
the first day of the week
 %W - week number of the current
year, starting with the first Monday as
the firstday of the first week
 %w - day of the week as a
decimal,Sunday=0
 %x - preferred date representation
withoutthe time
 %X - preferred time representation
withoutthe date
 %y - year without a century (range 00 to
99)
 %Y - year including the century
 %Z or %z - time zone or name
orabbreviation
 %% - a literal % character
strptime() Parses a time/date strptime(date,format);
generated with
strftime()
strtotime() Parses an English textual strtotime(time,now);
datetime into a Unix
timestamp
gettimeofday( Returns the current time gettimeofday(return_float);
)

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

Function Description Syntax


Count Returns the number count(array,mode);
ofelements in an where, array: specifies array
array mode: Optional. Specifies the mode.
Possiblevalues:
 0 - Default. Does not count all
elements of multidimensional
arrays
 1 - Counts the array
recursively(counts all the
elements of
multidimensional arrays)
list Assigns variables as list(var1,var2...)
ifthey were an array.
The list() function is
used to assign
values to a list of
variables in
one operation.
in_array Checks if a specified in_array(search,array,type)
value exists in an where,
array search: Required. Specifies the what to
search for
array: Required. Specifies the array to
searchtype: Optional. If this parameter is
set to TRUE, the in_array() function
searches for the search-string and specific
type in the
array.
current Returns the current current(array)
element in an array
next The next() function next(array)
moves the internal
pointer to, and
outputs,the next
element in the
array.
prev The prev() function prev(array)
moves the internal
pointer to, and
outputs,the previous
element in
the array.
end The end() function end(array)
moves the internal
pointer to, and
outputs,the last
element in the
array.
each The each() function each(array)
returns the current
element key and
value,and moves the
internalpointer
forward.
This element key
andvalue is returned
in an
array with four
elements. Two
elements (1 and
Value)for the
element value, and
two elements (0
and Key) for
theelement
key.
sort The sort() function sort(array,sortingtype);
sorts an indexed where,
arrayin ascending sortingtype:
order. pecifies how to compare the
arrayelements/items. Possible
values:
 0 = SORT_REGULAR - Default.
Compare items normally
(don't change types)
 1 = SORT_NUMERIC - Compare
items numerically
 2 = SORT_STRING - Compare items
as strings
 3 = SORT_LOCALE_STRING -
Compare items as strings, based
oncurrent locale
 4 = SORT_NATURAL - Compare
items as strings using natural
ordering
 5 = SORT_FLAG_CASE -
rsort The rsort() function rsort(array,sortingtype);
sorts an indexed
array
in descending order.
assort The asort() function asort(array,sortingtype);
sorts an associative
array in ascending
order, according to
the
value.
arsort The arsort() function arsort(array,sortingtype);
sorts an associative
array in descending
order, according to
the
value.
array_merge The array_merge() array_merge(array1,array2,array3...)
function merges one
ormore arrays into
one
array.
array_reverse The array_reverse() array_reverse(array,preserve)
function returns an
array in the reverse
order.
array_diff() The array_diff() array_diff(array1,array2,array3...);
function compares
thevalues of two (or
more) arrays, and
returns the
differences.
array_merge_recursive The array_merge_recursive(array1,array2,array
() array_merge_recursiv 3
e () function merges ...)
oneor more arrays
into one
array.
array_shift() The array_shift() array_shift(array)
function removes
thefirst element
from anarray, and
returns the
value of the
removedelement.
array_slice() The array_slice() array_slice(array,start,length,preserve)
function returns
selected parts of
an
array.
array_unique() The array_unique() array_unique(array)
function removes
duplicate values
from an array. If two
or more array values
are the same, the
first appearance will
be
kept and the other
willbe removed.
array_unshift() The array_unshift() array_unshift(array,value1,value2,value3...)
function inserts
new elements to an
array. The new
array valueswill be
inserted in the
beginning of the array.
array_keys() The array_keys() array_keys(array,value,strict)
function returns
an array
containing the
keys.

array_key_exists() checks an array for array_key_exists(key,array)


aspecified key, and
returns true if the
keyexists and false
if the
key does not exist.
array_push() inserts one or more array_push(array,value1,value2...)
elements to the end of
an array.
array_pop() deletes the last array_pop(array)
element
of an array.
array_multisort() The array_multisort(array1,sorting order,sorting
array_multisort() type,array2,array3...)
function returns a
sorted array. You
canassign one or
more arrays. The
function sorts the
first array, and the
other arrays follow,
then, if two ormore
values are the same,
it sorts the next
array, and so on.
array_search() The array_search() array_search(value,array,strict)
function search an
array for a value
andreturns the
key.

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

$my_array = array("Dog","Cat","Horse");

$people = array("Peter", "Joe", "Glenn", "Cleveland");

$people = array("Peter", "Joe", "Glenn", "Cleveland");echo


current($people) . "<br>";
echo next($people) . "<br>";
echo prev($people)."<br>";
echo end($people)."<br>";
print_r (each($people));
$numbers=array(4,6,2,22,11);
sort($numbers);

$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)

define("GREETING","Hello you! How are you today?");

define("GREETING","Hello you! How are you today?");

$site = "https://www.w3schools.com/";

$site = "https://www.w3schools.com/";

File handling Function


Function Description Syntax
fopen The fopen() function opens a fopen(filename,mode,include_path,c
fileor URL. ontext)
If fopen() fails, it returns FALSE Para
and an error on failure. You can Descriptio
hide the error output by adding nmeter
an'@' in front of the function
name. filena Required. Specifies
theme file or URL to open
mode Required. Specifies the
type of access you
requireto the
file/stream.
Possible values:
 "r" (Read only.
Starts at the
beginning of
thefile)
 "r+"
(Read/Write.
Starts at the
beginning of the
file)
 "w" (Write
only.Opens and
clearsthe
contents of file;
or creates a
new file if it
doesn't exist)
 "w+"
(Read/Write.
Opens and clears
the contents of
file; or creates a
new file if it
doesn't exist)
 "a" (Write only.
Opens and
writesto the end
of the file or
creates a new
file if it doesn't
exist)
 "a+"
(Read/Write.
Preserves file
content by
writingto the
end of the file)
 "x" (Write only.
Creates a new
file.Returns
FALSE and an
error if file
already exists)
 "x+" (Read/Write.
Creates a new
file.Returns
FALSE and an
error if file
already exists)
includ Optional. Set this
e_pat parameter to '1' if you
h want to search for the
filein the include_path
(in php.ini) as well
conte Optional. Specifies the
xt context of the file
handle.Context is a set
of optionsthat can
modify the behavior of
a stream
fread The fread() reads from an fread(file,length)
openfile.
The function will stop at the
end of the file or when it
reaches the specified length,
whichever comesfirst.
This function returns the read
string, or FALSE on failure.
fwrite The fwrite() writes to an open fwrite(file,string,length)
file.The function will stop at the
end of the file or when it
reaches the specified length,
whichever comesfirst.
This function returns the number
of bytes written, or FALSE
onfailure.
fclose The fclose() function closes fclose(file)
anopen file.
This function returns TRUE
onsuccess or FALSE on
failure.
file_exists The file_exists() function file_exists(path)
checks whether or not a file or
directoryexists.
This function returns TRUE if
the file or directory exists,
otherwise
it returns FALSE.
is_readable The is_readable() function checks is_readable(file)
whether the specified file is
readable.
This function returns TRUE if the
file is readable.
is_writable The is_writable() function checks is_writable(file)
whether the specified file is
writeable.
This function returns TRUE if the
file is writeable.
fgets The fgets() function returns a fgets(file,length)
linefrom an open file.
The fgets() function stops
returning on a new line, at the
specified length, or at
EOF,whichever comes
first.
This function returns FALSE on
failure.
fgetc returns a single character from fgetc(file)
an
open file.
file The file() reads a file into file(path,include_path,context)
anarray.
Each array element contains a line
from the file, with newline still
attached.
file_get_contents The file_get_contents() reads a file_get_contents(path,include_path,
file into a string. context,start,max_length)
This function is the preferred
wayto read the contents of a file
into astring. Because it will use
memorymapping techniques, if
this is supported by the server,
to
enhance performance.
fputcsv The fputcsv() function fputcsv(file,fields,separator,enclosu
formats aline as CSV and r e)
writes it to an open file.
This function returns the length
of
the written string, or FALSE
onfailure.
fputs The fputs() writes to an open fputs(file,string,length)
file. The function will stop at the
end of the file or when it
reaches the specified length,
whichever comesfirst.
This function returns the
numberof bytes written on
success, or FALSE on failure.
The fputs() function is an alias of
the fwrite() function.
file_putcontents The file_put_contents() writes a file_put_contents(file,data,mode,con
string to a file. text)
This function follows these rules
when accessing a file:
1. If FILE_USE_INCLUDE_P
ATH is set, check the
include path for a copy
of
*filename*
2. Create the file if it does
not exist
3. Open the file
4. Lock the file if LOCK_EXis
set
5. If FILE_APPEND is set,
move to the end of the
file.Otherwise, clear the
file content
6. Write the data into the file
7. Close the file and
releaseany locks
This function returns the
numberof character written
into the file
on success, or FALSE on failure.
ftell The ftell() function returns ftell(file)
the current position in an
open file.Returns the current
file pointer
position, or FALSE on failure.
fseek The fseek() function seeks in fseek(file,offset,whence)
anopen file.
This function moves the file
pointer from its current
position toa new position,
forward or backward, specified
by the number of bytes.
This function returns 0 on
success,
or -1 on failure. Seeking past
EOFwill not generate an error.
rewind The rewind() function rewind(file)
"rewinds" the position of the
file pointer to the beginning of
the file.
This function returns TRUE on
success, or FALSE on failure.
copy The copy() function copies a copy(file,to_file)
file.This function returns
TRUE on success and FALSE on
failure.
Unlink The unlink() function deletes a unlink(filename,context)
file.
This function returns TRUE on
success, or FALSE on failure.
rename The rename() function rename(oldname,newname,context
renames afile or directory. )
This function returns TRUE
onsuccess, or FALSE on
failure.
move_uploaded_file The move_uploaded_file() move_uploaded_file(file,newloc)
T. N. Rao College, Rajkot

function moves an uploaded


fileto a new location.
This function returns TRUE on
success, or FALSE on failure.

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);

echo "File written successfully";


?>
Example:
<?php
$file = fopen("test.txt","r");
//some code to be executed

fclose($file);
?>

Example:

139 Compiled by: Dr. Mital Vora


T. N. Rao College, Rajkot

<?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:

140 Compiled by: Dr. Mital Vora


T. N. Rao College, Rajkot

<?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");

// print current position


echo ftell($file);

14 by: Payal Malaviya


1
T. N. Rao College, Rajkot

// change current position


fseek($file,"15");

// print current position again


echo "<br />" . ftell($file);

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");

//Change position of file pointer


fseek($file,"15");

//Set file pointer to 0


rewind($file);

fclose($file);
?>

Example:
<?php
echo copy("source.txt","target.txt");
?>

Example:
<?php
$file = "test.txt";if
(!unlink($file))
{
echo ("Error deleting $file");
}
else

14 by: Payal Malaviya


2
Unit-1

{
echo ("Deleted $file");
}
?>

Example:
<?php
rename("images","pictures");
?>

You might also like