You are on page 1of 73

Reference : (1) www.javatpoint.com (2) www.w3schools.

com

PHP Forms and User Input


The PHP $_GET and $_POST variables are used to retrieve information from forms, like
user input.

We can create and use forms in PHP. To get form data, we need to use PHP superglobals
$_GET and $_POST.

The form request may be get or post. To retrieve data from get request, we need to use
$_GET, for post request $_POST.

PHP Get Form

Get request is the default form request. The data passed through get request is visible on
the URL browser so it is not secured. You can send limited amount of data through get
request.
Let's see a simple example to receive data from get request in PHP.
File: form1.html

<form action="welcome.php" method="get">


Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>

File: welcome.php

<?php
$name=$_GET["name"];//receiving name field value in $name variable

echo "Welcome, $name";


?>

PHP Post Form


Post request is widely used to submit form that have large amount of data such as file
upload, image upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so it is secured.
You can send large amount of data through post request.

Let's see a simple example to receive data from post request in PHP.

File: form1.html

<form action="login.php" method="post">


<table>

1
Reference : (1) www.javatpoint.com (2) www.w3schools.com

<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>

<tr><td>Password:</td><td> <input type="password" name="password"/


></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></t
r>
</table>
</form>
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variabl
e
$password=$_POST["password"];//receiving password field value in $
password variable

echo "Welcome: $name, your password is: $password";


?>

Output:

2
Reference : (1) www.javatpoint.com (2) www.w3schools.com

PHP Include and Require


PHP allows us to create various elements and functions, which are used several times in
many pages. It takes much time to script these functions in multiple pages. Therefore, use
the concept of file inclusion that helps to include files in various programs and saves the
effort of writing code multiple times.

"PHP allows you to include file so that a page content can be reused many times. It is very
helpful to include files when you want to apply the same HTML or PHP code to multiple
pages of a website." There are two ways to include file in PHP.

1. include
2. require

Both include and require are identical to each other, except failure.

o include only generates a warning, i.e., E_WARNING, and continue the execution
of the script.
o require generates a fatal error, i.e., E_COMPILE_ERROR, and stop the execution
of the script.

Advantage

Code Reusability: By the help of include and require construct, we can reuse HTML code
or PHP script in many PHP scripts.

Easy editable: If we want to change anything in webpages, edit the source file included in
all webpage rather than editing in all the files separately.

PHP include

PHP include is used to include a file on the basis of given path. You may use a relative or
absolute path of the file.

Syntax

There are two syntaxes available for include:

include 'filename ';


Or
include ('filename');

3
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Examples

Let's see a simple PHP include example.

File: menu.html

<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: include1.php

<?php include("menu.html"); ?>


<h1>This is Main Page</h1>

Output:

Home |
PHP |
Java |
HTML

This is Main Page

PHP require
PHP require is similar to include, which is also used to include files. The only difference
is that it stops the execution of script if the file is not found whereas include doesn't.

Syntax

There are two syntaxes available for require:

require 'filename';
Or
require ('filename');

Examples

Let's see a simple PHP require example.

File: menu.html

<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>
4
Reference : (1) www.javatpoint.com (2) www.w3schools.com

File: require1.php

<?php require("menu.html"); ?>


<h1>This is Main Page</h1>

Output:

Home |
PHP |
Java |
HTML
This is Main Page

PHP include vs PHP require


Both include and require are same. But if the file is missing or inclusion
fails, include allows the script to continue but require halts the script producing a fatal
E_COMPILE_ERROR level error.

Let's understand the difference with the help of example:

Example
include.php

<?php
//include welcome.php file
include("welcome.php");
echo "The welcome file is included.";
?>

Output:

The welcome.php file is not available in the same directory, which we have included. So,
it will produce a warning about that missing file but also display the output.

Warning: include(welcome.php): failed to open stream: No such file or directory in


C:\xampp\htdocs\program\include.php on line 3

Warning: include(): Failed opening 'welcome.php' for inclusion


(include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\program\include.php on line 3
The welcome file is included.
require.php

<?php
echo "HELLO";
//require welcome.php file
require("welcome.php");

5
Reference : (1) www.javatpoint.com (2) www.w3schools.com

echo "The welcome file is required.";


?>

Output:

In case of require() if the file (welcome.php) is not found in the same directory. The
require() will generate a fatal error and stop the execution of the script, as you can see in
the below output.

HELLO
Warning: require(Welcome.php): failed to open stream: No such file or directory in
C:\xampp\htdocs\program\include.php on line 3

Fatal error: require(): Failed opening required 'Welcome.php'


(include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\program\include.php on line 3

PHP Functions

PHP functions are similar to other programming languages. A function is a piece of


code which takes one more input in the form of parameter and does some processing
and returns a value.

There are two parts which should be clear to you:

 Creating a PHP Function


 Calling a PHP Function

In fact you hardly need to create your own PHP function because there are already
more than 1000 of built-in library functions created for different area and you just
need to call them according to your requirement.

Creating PHP Function:

Its very easy to create your own PHP function. Suppose you want to create a PHP
function which will simply write a simple message on your browser when you will
call it. Following example creates a function called writeMessage() and then calls it just
after creating it.

Note that while creating a function its name should start with keyword function and all
the PHP code should be put inside { and } braces as shown in the following example
below:

6
Reference : (1) www.javatpoint.com (2) www.w3schools.com

<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP
Function */
writeMessage();
?>
</body>
</html>

This will display following result:

7
Reference : (1) www.javatpoint.com (2) www.w3schools.com

You are really a nice person, Have a nice time!

PHP Functions with Parameters:

PHP gives you option to pass your parameters inside a function. You can pass as
many as parameters your like. These parameters work like variables inside your
function. Following example takes two integer parameters and add them together and
then print them.

<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>

This will display following result:

Sum of the two numbers is : 30

Passing Arguments by Reference:

It is possible to pass arguments to functions by reference. This means that a reference


to the variable is manipulated by the function rather than a copy of the variable's value.

Any changes made to an argument in these cases will change the value of the original
8
Reference : (1) www.javatpoint.com (2) www.w3schools.com

variable. You can pass an argument by reference by adding an ampersand to the


variable name in either the function call or the function definition.

Following example depicts both the cases.

<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
$num += 5;
}

function addSix(&$num)
{
$num += 6;
}

$orignum = 10;
addFive($orignum;
echo "Original Value is
$orignum<br />";

addSix( $orignum );

echo "Original Value is $orignum<br />";


?>
</body>
</html>

9
Reference : (1) www.javatpoint.com (2) www.w3schools.com

This will display following result:

Original Value is 15
Original Value is 21

PHP Functions returning value:

A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the calling
code.

You can return more than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and then returns
their sum to the calling program. Note that return keyword is used to return a value
from a function.

<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value
?>
</body>
</html>

This will display following result:

Returned value from the function : 30

10
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Setting Default Values for Function Parameters:

You can set a parameter to have a default value if the function's caller doesn't pass
it. Following function prints NULL in case use does not pass any value to this
function.

<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is
test"); printMe();
?>
</body>
</html>

11
Reference : (1) www.javatpoint.com (2) www.w3schools.com

This will produce following result:


This is test

Dynamic Function Calls:

It is possible to assign function names as strings to variables and then treat these
variables exactly as you would the function name itself. Following example depicts this
behaviour.

<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>

This will display following result:

Hello

12
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Library Functions in PHP

PHP Math Functions


PHP provides many predefined math constants and functions that can be used to perform
mathematical operations.

(1) abs() Function

The abs() function returns absolute value of given number. It returns an integer value but if
you pass floating point value, it returns a float value.

Syntax
number abs ( mixed $number )

Example
<?php
echo (abs(-7)."<br/>"); // 7 (integer)
echo (abs(7)."<br/>"); //7 (integer)
echo (abs(-7.2)."<br/>"); //7.2 (float/double)
?>

Output:

7
7
7.2

(2) ceil() Function

The ceil() function rounds fractions up.

Syntax

float ceil ( float $value )

Example
<?php
echo (ceil(3.3)."<br/>");// 4
echo (ceil(7.333)."<br/>");// 8
echo (ceil(-4.8)."<br/>");// -4 -4 -4.8 -5
?>

Output:

13
Reference : (1) www.javatpoint.com (2) www.w3schools.com

4
8
-4

(3) floor() Function

The floor() function rounds fractions down.

Syntax

float floor ( float $value )

Example
<?php
echo (floor(3.3)."<br/>");// 3
echo (floor(7.333)."<br/>");// 7
echo (floor(-4.8)."<br/>");// -5
?>

Output:

3
7
-5

(4) sqrt() Function

The sqrt() function returns square root of given argument.

Syntax

float sqrt ( float $arg )

Example

<?php
echo (sqrt(16)."<br/>");// 4
echo (sqrt(25)."<br/>");// 5
echo (sqrt(7)."<br/>");// 2.6457513110646
?>

Output:

4
5
2.6457513110646

14
Reference : (1) www.javatpoint.com (2) www.w3schools.com

(5) decbin() function

The decbin() function converts decimal number into binary. It returns binary number as a
string.

Syntax

string decbin ( int $number )

Example
<?php
echo (decbin(2)."<br/>");// 10
echo (decbin(10)."<br/>");// 1010
echo (decbin(22)."<br/>");// 10110
?>

Output:

10
1010
10110

(6) dechex() Function

The dechex() function converts decimal number into hexadecimal. It returns hexadecimal
representation of given number as a string.

Syntax

string dechex ( int $number )


Example
<?php
echo (dechex(2)."<br/>");// 2
echo (dechex(10)."<br/>");// a
echo (dechex(22)."<br/>");// 16
?>

Output:

2
a
16

(7) decoct() function

The decoct() function converts decimal number into octal. It returns octal representation of
given number as a string.

15
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Syntax

string decoct ( int $number )


Example
<?php
echo (decoct(2)."<br/>");// 2
echo (decoct(10)."<br/>");// 12
echo (decoct(22)."<br/>");// 26
?>

Output:

2
12
26

(8) base_convert() Function

The base_convert() function allows you to convert any base number to any base number. For
example, you can convert hexadecimal number to binary, hexadecimal to octal, binary to
octal, octal to hexadecimal, binary to decimal etc.

Syntax

string base_convert ( string $number , int $frombase , int $tobase )

Example
<?php
$n1=10;
echo (base_convert($n1,10,2)."<br/>");// 1010
?>

Output:

1010

(9) bindec() Function

The bindec() function converts binary number into decimal.

Syntax

number bindec ( string $binary_string )

Example
<?php

16
Reference : (1) www.javatpoint.com (2) www.w3schools.com

echo (bindec(10)."<br/>");// 2
echo (bindec(1010)."<br/>");// 10
echo (bindec(1011)."<br/>");// 11
?>

Output:

2
10
11

(10) Max() Function

The max() function is used to find the highest value.

Syntax:
max(array_values);

OR

max(value1,value2,value3,value4...);
Name Description Required/Optional

array_values Specifies an array containing the Required


values

value1,value2,value3,value4... Specifies the values to compare Required


(must be at least two values

Example1
<?php
$num=max(4,14,3,5,14.2);
echo "Your number is =max(4,14,3,5,14.2)".'<br>';
echo "By using max function Your number is : ".$num;
?>

Output:

Your number is =max(4,14,3,5,14.2)


By using max function Your number is : 14.2

17
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Example2

<?php
$num=max(.1, .001, .2, -.5);
echo "Your number is =max(.1, .001, .2, -.5)".'<br>';
echo "By using max function Your number is : ".$num;
?>

Output:

Your number is =max(.1, .001, .2, -.5)


By using max function Your number is : 0.2
Example3
<?php
$arr= array(110, 20, 52 ,105, 56, 89, 96);
echo "Your number is =array(110, 20, 52 ,105, 56, 89, 96)".'<br>';

echo "By using max() function Your number is : ".max($arr);


?>

Output:

Your number is =array(110, 20, 52 ,105, 56, 89, 96)


By using max() function Your number is : 110

(11) Min() Function


PHP min() function is used to find the lowest value.

Syntax:
min(array_values);
or
min(value1,value2,value3...);
Parameter Description

array_values Specified array

value1,value2,value3...); Specifies the two or more value (at least two numbers).

Example1
<?php
$num=min(4,14,3,5,14.2);
echo "Your number is =min(4,14,3,5,14.2)".'<br>';
echo "By using min() function Your number is : ".$num;

18
Reference : (1) www.javatpoint.com (2) www.w3schools.com

?>

Output:

Your number is =max(4,14,3,5,14.2)


By using min function Your number is : 3
Example2
<?php
$num=min(4,-14,3,-5,14.2);
echo "Your number is =min(4,-14,3,5,14.2)".'<br>';
echo "By using min() function Your number is : ".$num;
?>

Output:

Your number is =min(4,-14,3,5,14.2)


By using min() function Your number is : -14

Example3
<?php
$ar=array(14,-18,4,8,15.5);
echo "Your number is =min(14,-18,4,8,15.5)".'<br>';
echo "By using min() function Your number is : ".min($ar);
?>

Output:

Your number is =min(14,-18,4,8,15.5)


By using min() function Your number is : -18
Example4
<?php
$ar=array(1=>15,3=>25,4=>13,5=>10);
echo "Your number is =min(1=>15,3=>25,4=>13,5=>10)".'<br>';
echo "By using min() function Your number is : ".min($ar);
?>

Output:

Your number is =min(1=>15,3=>25,4=>13,5=>10)


By using min() function Your number is : 10

(12) pow() function


The pow() is a PHP mathematic function. It raises the first number to the power of the second
number.

19
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Syntax:
number pow ( number $base , number $exp )
Parameter Description Required /Optional

Base Required. Specifies the base to use. required

Exp Required. Specifies the exponent. required

Return Value: Returns a number (floating-point & Integer) which is equal to $base raised to
the power of $exponent.

Example 1
<?php
$num=pow(3, 2);
echo "Your number is = pow (3, 2)".'<br>';
echo "By using sqrt function Your number is : ".$num;
?>

Output:

Your number is =pow(3, 2)


By using sqrt function Your number is : 9
Example 2

<?php
$num=pow(-4, 2);
echo "Your number is = pow (-4, 2)".'<br>';
echo "By using sqrt function Your number is : ".$num;
?>

Output:

Your number is = pow (-4, 2)


By using sqrt function Your number is : 16
Example3

<?php
$num=pow(-3, -3);
echo "Your number is =pow(-3, -3)".'<br>';
echo "By using sqrt function Your number is : ".$num;
?>

Example 4
<?php

20
Reference : (1) www.javatpoint.com (2) www.w3schools.com

for($i=1;$i<=5;$i++)
{
echo "The power value of [$i] is". "=".pow($i,2)."<br>";
}
?>

Output:

The power value of [1] is=1


The power value of [2] is=4
The power value of [3] is=9
The power value of [4] is=16
The power value of [5] is=25

(13) rand() Function

The rand() function generates a random integer.

Tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100).

Syntax
rand();
or
rand(min,max);

Parameter Values

Parameter Description

Min Optional. Specifies the lowest number to be returned. Default is 0

Max Optional. Specifies the highest number to be returned. Default is getrandmax()

Example
Generate random numbers:

<?php
echo(rand() . "<br>");
echo(rand() . "<br>");

21
Reference : (1) www.javatpoint.com (2) www.w3schools.com

echo(rand(10,100));
?>

String Functions
1) strtolower() function
The strtolower() function returns string in lowercase letter.

Syntax

string strtolower ( string $string )

Example

<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
?>

Output:

my name is khan

2) strtoupper() function
The strtoupper() function returns string in uppercase letter.

Syntax

string strtoupper ( string $string )

Example

<?php
$str="My name is KHAN";
$str=strtoupper($str);
echo $str;
?>

Output:

MY NAME IS KHAN

22
Reference : (1) www.javatpoint.com (2) www.w3schools.com

3) ucfirst() function
The ucfirst() function returns string converting first character into uppercase. It doesn't
change the case of other characters.

Syntax

string ucfirst ( string $str )

Example

<?php
$str="my name is KHAN";
$str=ucfirst($str);
echo $str;
?>

Output:

My name is KHAN

4) ucwords() function
The ucwords() function returns string converting first character of each word into uppercase.

Syntax

string ucwords ( string $str )

Example

<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str);
echo $str;
?>

Output:

My Name Is Sonoo Jaiswal

5) strrev() function
The strrev() function returns reversed string.

Syntax

string strrev ( string $string )

23
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Example

<?php
$str="my name is Sonoo jaiswal";
$str=strrev($str);
echo $str;
?>

Output:

lawsiaj oonoS si eman ym

6) strlen() function
The strlen() function returns length of the string.

Syntax

int strlen ( string $string )

Example

<?php
$str="my name is Sonoo jaiswal";
$str=strlen($str);
echo $str;
?>

Output:

24

7) addslashes() function
PHP addslashes() function is used to return a quote string with slashes. It works with some
characters:

o Single quote (')


o Double quote(")
o Blackslash(|)
o NUL (the NUL byte)

Syntax:
string addslashes (string $str );

24
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Parameter Description Required/Optional

String String to be escaped Required

Example 1

<?php
$str = 'What does "WHO" mean?';
echo "Your string is :".$str;
echo "<br>"."By using addslashes() function the result is".addslash
es($str);
?>

Output:

Your string is :What does "WHO" mean?


By using addslashes() function the result isWhat does \"WHO\" mean?
Example 2
<?php
$str = "Who's the father of PHP?";
echo $str . " This is not safe in a database query.<br>";
echo addslashes($str) . " This is safe in a database query.";

?>

Output:

Who's the father of PHP? This is not safe in a database query.


Who\'s the father of PHP? This is safe in a database query.

(8) chr() Function


The PHP chr() function is used to generate a single byte string from a number. In another
words we can say that it returns a character from specified ASCII value.

Syntax:
string chr ( int $bytevalue );

Example 1

<?php
$char =52;
echo "Your character is :".$char;
echo "<br>"."By using 'chr()' function your value is: ".chr($char)
;// decimal Value
25
Reference : (1) www.javatpoint.com (2) www.w3schools.com

?>

Output:

Your character is :52


By using 'chr()' function your value is: 4

(9) ltrim() function


PHP string ltrim() function is predefined function. It is often used to remove whitespace from
both sides of a string or other character from the left side of a string.

Syntax:
ltrim(string,charlist);

Example 1
<?php
$str = " Hello PHP!";
echo "Without ltrim() Function: " . $str;
echo "<br>";
echo "With ltrim() function : " . ltrim($str);
?>

Output:

Without ltrim() Function: Hello PHP!


With ltrim() function : Hello PHP!
Note: To remove newlines from the left side of a string then we can use (\n):

(10) rtrim() Function

PHP rtrim() is predefined function which is used to remove whitespace or character form the
right side of a string.

Syntax:
rtrim(string,charlist);

Example 1
<?php
$str = "Hello PHP! ";
echo "Without rtrim() function: " . $str;
echo "<br>";
echo "With rtrim() function:" . rtrim($str);
?>

Output:

26
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Without rtrim() function: Hello PHP!


With rtrim() function:Hello PHP!

(11) trim() function

PHP string trim() function is in-built function. It is used to strip whitespace from the
beginning and end of a string or both side of a string.

Syntax:
trim(string,charlist);

Example 1
<?php
$str = "\n\n\nHello PHP!\n\n\n";
echo "Without trim() function: ". $str;
echo "<br>";
echo "With trim() function: ". trim($str);
?>

Output:

Without trim() function: Hello PHP!


With trim() function: Hello PHP!

Example 2
<?php
$str = "Hello PHP!";
echo "Your string is: ".$str ."<br>";
echo "By using trim() function :".trim($str,"Hed!");
?>

Output:

Your string is: Hello PHP!


By using trim() function :llo PHP

(12) substr() Function

The substr() is a built-in function of PHP, which is used to extract a part of a string. The
substr() function returns a part of a string specified by the start and length parameter. PHP
4 and above versions support this function.

Syntax

The syntax of the substr() function is given below. It contains three parameters, in which two
are mandatory, and one is optional.

27
Reference : (1) www.javatpoint.com (2) www.w3schools.com

substr(string,start,length)

Parameters

$string (required) - It is the main string parameter, which specifies the string that needs to
be cut or modified. This is a mandatory parameter of this function. It specifies the input string
that must be one character or longer.

$start (required) - This is also a mandatory parameter of this function as $string. It specifies
that from where to start extraction in the string. This parameter contains an integer value,
which has three conditions:

o If $start has a positive value, then the returned string will start from $startth position
in the string, and counting begins from zero.
o If $start has a negative value, then the returned string will start from $startth character
from the end of the string. In this case, counting begins from -1 not from zero at the
end of the string.
o If the $string size is less than $start value, then it will return FALSE.

$length (optional) - This is an integer type and optional parameter of this function. This
parameter has the length of the string to be cut from the main string. It has the following
conditions:

o If $length is positive, then the returned string will contain the number of character
passed in $length parameter that will begin from the $start.
o If $length is negative, then it begins from $start position and extracts the length from
the end of the string. Many of the characters will be omitted from the end of the string
if the value passed in $length parameter is negative.
o If the value passed in $length parameter is zero, FALSE or NULL, then an empty
string will be returned (See in example 3).
o If the $length parameter is not passed, then substr() function will return a string
starting from $start till the end of the string.

Return Values

The substr() function returns an extracted part of the string on successful execution.
Otherwise, it returns the FALSE or empty string on failure.

Changelog
o In PHP 7.0.0, if $string is equal to the $start, then substr() function returns an empty
string. Before this version, FALSE was returned in this case.
o In PHP 5.2.2 - PHP 5.2.6, if the $start parameter indicates the position of negative
truncation or beyond, then FALSE will be returned, whereas other versions get the
string from $start.

Examples

28
Reference : (1) www.javatpoint.com (2) www.w3schools.com

There are some examples given, through which we can learn the working of the substr()
function. Let's see the below examples-

Example 1

<?php
//Positive value passed in $start
echo substr("Hello javaTpoint", 3). "</br>";
echo substr("Hello javaTpoint", 0). "</br>";
echo substr("Hello javaTpoint", 9). "</br>";

//Negative value passed in $start


echo substr("Hello javaTpoint", -4). "</br>";
echo substr("Hello javaTpoint", -10). "</br>";
echo substr("Hello javaTpoint", -16). "</br>";
?>

Output:

The output for the above program is given below.

lo javaTpoint
Hello javaTpoint
aTpoint
oint
JavaTpoint
Hello javaTpoint

Example 2

<?php
//By passing both $start and $length parameter
echo substr("Hello javaTpoint", 3, 8). "</br>";
echo substr("Hello javaTpoint", 0, 9). "</br>";
echo substr("Hello javaTpoint", 6, -4). "</br>";

echo substr("Hello javaTpoint", 4, -7). "</br>";


echo substr("Hello javaTpoint", -6, -1). "</br>";
echo substr("Hello javaTpoint", -6, -10). "</br>";
?>

Output:

The output for the above program is given below.

lo javaT
Hello jav
javaTp
o jav

29
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Tpoin

Example 3

<?php
//By passing zero in $length parameter
echo substr("Hello javaTpoint", 7, 0). "</br>";
?>

Output:

When a zero or Null value is passed in $length, then the substr() function returns an empty
string.

No output

(13) strcmp() Function

String comparison is one of the most common tasks in programming and development.
strcmp() is a string comparison function in PHP. It is a built-in function of PHP, which
is case sensitive, means it treats capital and the small case separately. It is used to compare
two strings from each other. This function compares two strings and tells whether a string is
greater, less, or equal to another string. strcmp() function is binary safe string comparison.

Note: strcmp() function is case sensitive as well as binary safe string comparison.
Syntax:
strcmp($str1, $str2);
Parameters

strcmp() function accepts two strings parameter, which is mandatory to pass in the function
body. Both parameters are mandatory to pass in strcmp() function(). Description of the
following parameters is given below.

1. $str1 - It is the first parameter of strcmp() function that is used in the comparison.
2. $str2 - It is the second parameter of strcmp() function to be used in the comparison.

Value return by strcmp()

This function returns integer value randomly based on the comparison.

Return 0 - It returns 0 if both strings are equal, i.e., $str1 = $str2

Return < 0 - It returns negative value if string1 is less than string2, i.e., $str1 < $str2

Return >0 - It returns positive value if string1 is greater than string 2, i.e., $str1 > $str2

30
Reference : (1) www.javatpoint.com (2) www.w3schools.com

<?php
echo strcmp("Hello ", "HELLO"). " because the first string is g
reater than the second string.";
echo "</br>";
echo strcmp("Hello world", "Hello world Hello"). " because the
first string is less than the second string.";
?>

Output:

1 because the first string is greater than the second string.


-6 because the first string is less than the second string.

Remark: Second string comparison has returned -6 because the first string is 6 characters
smaller than the second string, including whitespace.

(14) strcasecmp() function

PHP string strcasecmp() is predefine function. It is used to compare two given string. It is and
case-insensitive.

It returns:

o If the two strings are equal: [ 0 ]


o If string1 is less than string2: [< 0]
o If string1 is greater than string2: > 0

Syntax:
strcasecmp(string1,string2);
Parameter Description Required/Optional

string 1 Specify first string to compare. Required.

String2 Specify the second string to compare. Reuired.

Example 1
<?php
$str1 = "JavaTPOINT";
$str2 = "JAVAtpoint";
echo "Your first string is:".$str1;
echo "<br>";
echo "Your second string is:".$str2;
echo "<br>";
echo strcasecmp("$str1","$str2");
?>

Output:

31
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Your first string is:JavaTPOINT


Your second string is:JAVAtpoint
0
Example 2
<?php
echo "By using strcasecmp() function:".strcasecmp("Hello","HELLO
");
echo "<br>";
echo "using strcasecmp() function:".strcasecmp("Hello","hELLo");

?>

Output:

By using strcasecmp() function:0


using strcasecmp() function:0

(15) strpos() Function

The strops() is in-built function of PHP. It is used to find the position of the first occurrence
of a string inside another string or substring in a string.

Syntax:
int strpos ( string $haystack, mixed $needle[, int $offset = 0 ] );

Parameter Description Required/Optional

String Specify the string to search. Start

Find Specify the string to find. Required

Start Specify where to begin the search. Optional

This function will help us to find the numeric position of the first occurrence of needle in the
haystack string

Note: The strops() function is case-sensitive and binary-safe.


Example 1
<?php
$str1="Hello Php";
$str2="Hello Php javatpoint!";
echo "First string is: ".$str1;
echo "<br>";
echo "First string is: ".$str2;
echo "<br>";

32
Reference : (1) www.javatpoint.com (2) www.w3schools.com

echo "By using 'strpos()' function:".strpos("$str1,$str2","php


");
//$str1 and $str2 'Php'first letter is upper case so output is
nothing.
// It is case-sensitive
?>

Output:

First string is: Hello Php


First string is: Hello Php javatpoint!
By using 'strpos()' function:
Example 2
<?php
$str1="Hello php";
$str2=" Hello php javatpoint!";
echo "First string is: ".$str1;
echo "<br>";
echo "First string is: ".$str2;
echo "<br>";
echo "By using 'strpos()' function:".strpos("$str1,$str2","php
");
//Find the position of the first occurrence of "php" inside th
e string
?>

Output:

First string is: Hello php


First string is: Hello php javatpoint!
By using 'strpos()' function:6
Example 3
<?php
$mystring = 'Hello PHP';
$findme = 'Hello';
$pos = strpos($mystring, $findme);

// Note our use of ===. Simply == would not work as expected


// because the position of 'Hello' was the 0th (first) character.

if ($pos === false) {


echo "The string '$findme' was not found in the string '$mystr
ing'";
} else {
echo "The string '$findme' was found in the string '$mystring'
";
echo "<br>";
echo " and exists at position $pos";
}

33
Reference : (1) www.javatpoint.com (2) www.w3schools.com

?>

Output:

The string 'Hello' was found in the string 'Hello PHP'


and exists at position 0

(16) String strrpos() function

The strrpos() is an in-built function of PHP which is used to find the position of the last
occurrence of a substring inside another string. It is a case-sensitive function of PHP, which
means it treats uppercase and lowercase characters differently.

The strrpos() is similar to the strripos(), which is also used to find the last occurrence of the
substring inside another string, but strripos() is a case-insensitive function whereas strrpos()
is a case-sensitive function. PHP 4+ versions support this function.

There are some related functions of PHP which is similar to the strrpos() function:

Related functions
o stripos() - It finds the first occurrence of a string inside another string. (Case-
insensitive)
o strpos() - It finds the first occurrence of a string inside another string. (Case-sensitive)
o strripos() - It finds the last occurrence of a string inside another string. (Case-
insensitive)

Syntax

The syntax for the following function strrpos() is:

1. strrpos ($string, $search, $start)


Parameter

The strrpos() function accepts three parameters in which two are mandatory, i.e., the main
string and the search string. The third parameter is optional, that is $start, from where we start
the search of the string.

$string (required) - It is a mandatory parameter in which we search the occurrence of the


$search string.

$search (required) - It is also a mandatory parameter which specifies the string which is to
be searched.

$start (optional) - It is the last and optional parameter of this function which specifies that
from where to begin the search. This parameter has an integer value.

Return Values

34
Reference : (1) www.javatpoint.com (2) www.w3schools.com

The strrpos() function returns the position of the last occurrence of a substring inside
another string. If the string is not found, then it will return FALSE.

It is important to note that the string position starts from 0, not from 1.

Changelogs
o PHP 5.0 included a new parameter $start in strrpos() function which defines that from
where to begin the search.
o After PHP 5.0, we can also pass a string in $search parameter rather than passing only
a single character.

Examples

There are some detailed examples to learn the functionality of the strrpos() function. These
examples will provide the basic knowledge of this function.

Example 1

Below is the basic example of strrpos():

<?php
$string = "Hello! I'm Mishti Agrawal";
$search ='gra';
$output1 = strripos( $string, $search );
echo "The last occurrence of the search string is found at posit
ion: ".$output1;
?>

Output:

The output for the above program will be-

The last occurrence of the search string is found at position: 19

Example 2

<?php
$string = "Hello everyone! Welcome to javaTpoint";
$search ='l';
$output1 = strripos( $string, $search );
echo "The last occurrence of the search string is found at posit
ion: ".$output1;
?>

Output:

In this above example, the last occurrence of "l" is 16.

The last occurrence of the search string is found at position: 16

35
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Example 3: Case-sensitive

<?php
$string = "Welcome to javaTpoint";
$search ='COME';
$res1 = strripos( $string, $search );
echo $res1."</br>";
echo "Search string is not found, so it returned: ";
var_dump($res1);
?>

Output:

This example has proved that strrpos() is a case-sensitive function, as it treated "COME" and
"come" differently. The output for the above program will be-

Search string is not found, so it returned: bool(false)

Example 4

In this example, the search string is not available in the main string, so it will return Boolean
value FALSE.

<?php
$string = "Welcome to javaTpoint";
$search ='misthi';
$res1 = strripos( $string, $search );
echo $res1."</br>";
echo "Search string is not found so it returned: ";
var_dump($res1);
?>

Output:

Echo is not sufficient to display the Boolean value, so we use var_dump() function to print
that Boolean value FALSE.

Search string is not found so it returned: bool(false)

Example 5

Below example contains if-else condition. If the string is not found, it will show that search
string is not found otherwise, it will display the position of the last occurrence of the search
string.

<?php
$string = "Welcome to javaTpoint";
$search1 ='cml';
36
Reference : (1) www.javatpoint.com (2) www.w3schools.com

$search2="ome";
$res1 = strrpos( $string, $search1);
if($res1==false)
echo "Sorry! <b>". $search1. "</b> is not found in the strin
g";
else
echo "The following search string <b>". $search1. "</b> find
at position: ".$res1;

echo '</br>';
$res2 = strrpos( $string, $search2);
if($res2==false)
echo "Sorry! string is not found";
else
echo "The following search string <b>". $search2. "</b> is f
ound at position: ".$res2;
?>

Output:

Sorry! cml is not found in the string


The following search string ome is found at position: 4

Example 6: By using length parameter

<?php

$string = "Welcome to javaTpoint";


$search2="Wel";
$position = strrpos($string, $search2, 7);
if ($position == true){
echo "Found at position " . $position;
}
else{
echo "Search string is not found.";
}
?>

Output:

In the above example, "Wel" is present in the main string; still it displays the output that
"search string is not found." It is because the searching is started from 7th position, but "Wel"
is available at 1st position.

Search string is not found.

Example 7

<?php

37
Reference : (1) www.javatpoint.com (2) www.w3schools.com

$string = "Welcome to javaTpoint";


$search="ava";
$position = strripos($string, $search, 4);
if ($position == true){
echo $search. " is found at position " . $position;

}
else{
echo "Search string not Found";
}
?>

Output:

In the above example, strrpos() start searching from 4th position. It found search string at
12th position.

ava is found at position 12

(17) strstr() function


The strstr() function is an in-built function of PHP. It is a case-sensitive function which finds
the first occurrence of a string. The strstr() is mainly used to search the first occurrence of a
string inside another string and displays some part of the latter starting from the first
occurrence of the former in latter.

Syntax

The syntax for the PHP strstr() function is given below, which consists three parameters.

stristr ($string, $search, $before_search)

Parameters

$string (required): $string is a mandatory parameter which specifies the string to be


searched. In other words, it is the main string parameter in which $search value is searched.

$search (required): The next mandatory parameter of this function is $search. It specifies
that string which is going to be searched in $string parameter. If this parameter contains a
number or integer value rather than a string, then it will search for character matching ASCII
value for that number.

$before_search (optional): It is the last and optional parameter of strstr() function which
specifies the Boolean value, whose default value is FALSE. If we set it to TRUE, then it will
return the part of the string before the first occurrence of the search parameter.

Return Values

38
Reference : (1) www.javatpoint.com (2) www.w3schools.com

The PHP strstr() returns the remaining string (from the matching point), or it will
return FALSE if the string which we are searching for is not found.

Technical Details
PHP version PHP 4+ versions support this function.
support

Return Values The strstr() returns rest of the string or returns False if the string for
search is not found.

ChangeLog o In strstr(), $before_search parameter was added in PHP 5.3

Examples of strstr()

There are some examples given below that will help us to learn the practical use of this
function.

//Returns remaining string after search found


Input:
$string1 = "Hello! Good Morning everyone", $search1 = "Good";
Output: Morning everyone

//case-sensitive, returns nothing


Input:
$string = "Hello! Good Morning everyone ", $search = "HELLO ";
Output:

//Returns initial string when search found


Input:
$string = "Hello! Good Morning everyone", $search = "Good", before_search = true;
Output: Hello!

//Passing ASCII value of r which is 114


Input:
$string = "I want to travel the world ", $search = "114", before_search = true;
Output: I want to t

Below some detailed examples are given. With the help of these examples, we can
understand the use of this function in a much better way.

Example 1

39
Reference : (1) www.javatpoint.com (2) www.w3schools.com

It is a simple example of strstr() which shows that it is a case-sensitive function, so it returns


FALSE if the string does not match. It will return the rest of the string from where the
$search variable will find in the string.

<?php
$string = "Welcome to javaTpoint";
$search1 = "e";
echo strstr($string, $search1);

echo '</br>';
$search2 = "JAVA"; //case-sensitive
var_dump(strstr($string, $search2));

echo '</br>';
var_dump(strstr($string, "WeLcOmE"));
?>

Output:

Example 2

In this below example, we will use a third parameter $before_search, whose default value
is FALSE. Here, we will set it to TRUE, which will return the part of the string before the
first occurrence of the $search parameter. If the search string is not found, then it will return
the Boolean value false.

<?php
$string = "Welcome to javaTpoint website.";
$before_search = true;
$search1 = "a";
echo strstr($string, $search1, $before_search);

echo '</br>';
$search2 = "E";
var_dump(strstr($string, $search2, $before_search));

echo '</br>';
$search3 = "nt";
echo strstr($string, $search3, $before_search);
?>

40
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Output:

(18) stristr() function in PHP


The stristr() is an in-built function of PHP which is used to search the first occurrence of the
string inside another string, and it returns rest of the string if the string is present. It is
a binary-safe function (Binary safe function means - a function which can be performed on
binary file without modifying the content of the file).

The stristr() is a case-insensitive function which is similar to the strstr(). Both functions are
used to search a string inside another string. The only difference between them is that stristr()
is case-insensitive whereas strstr() is case-sensitive function.

Note: This function is binary-safe and case-insensitive function. In stristr() function 'I' stands
for insensitive.
Syntax

The syntax for the PHP stristr() function is as follows:

stristr ($string, $search, $before_search)

Parameter

$string (required): This parameter is a mandatory parameter which specifies the string
which is to be searched, means it is the main string in which $search (discussed next) value is
searched.

$search (required): This parameter is also mandatory as $string. This parameter specifies
the string which is going to be searched in $string. If this parameter is a number or integer
value rather than a string, then it will use it as ASCII value.

$before_search (optional): This parameter is an optional parameter which specifies the


Boolean value whose default value is FALSE. If we set it to TRUE, then it will return the
part of the string before the first occurrence of the search parameter.

41
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Return Values

The PHP stristr() returns the remaining string (starts from the matching point), or it will
return FALSE, if the string which we are searching for is not found.

Technical Details
PHP version PHP 4 and above versions support this function.
support

Return Values It returns rest of the string or returns False if the string to be
searched is not found.

ChangeLog o In PHP 5.3, the before_search parameter was added in this


function.
o The stristr() function became a binary-safe function in PHP
4.3.

Examples

Below are some examples through which you can learn the practical implementation of the
stristr() function in the program.

Input:
$string = "Hello PHP! ", $search = "PHP ";
Output: PHP!

Input:
$string = "Hello PHP! ", $search = "p ", before_search = true; //case-insensitive
Output: Hello

Input:
$string = "Hello PHP! ", $search = "K ", before_search = true;
Output:

Following are some detailed examples which are given below -

Example 1

It is the simple example of stristr() which shows that it is case-insensitive function and return
the rest of the string where the $search variable will find.

<?php
$string = "Welcome to javaTpoint";
$search1 = "a";
echo stristr($string, $search1);

42
Reference : (1) www.javatpoint.com (2) www.w3schools.com

echo '</br>';
$search2 = "J"; //case-insensitive
echo stristr($string, $search2);

echo '</br>';
echo stristr($string, "WELcoME");
?>

Output:

(19) str_replace() function


The str_replace() function is a case-sensitive, built-in function of PHP which replaces some
character of the string with other characters. It is used to replace all the occurrences of the
search string with the replacement string.

Syntax

The syntax of the str_replace() function is given below, which has the following four
parameters.

str_replace ( $search, $replace, $string, $count)

This function follows some rules while working, which are given below:

o If the string which is to be searched is an array, it returns an array.


o If the string which is to be searched is an array then search and replace is performed
with each element of the array.
o If both $search and $replace are arrays and $replace has fewer elements than $search
array, then an empty string will be used as replace.
o If the $search is an array, but $replace is a string, then the replace string will be used
for every search value.

Parameter

The str_replace() function has four parameters in which three are mandatory, and the
remaining one is an optional parameter. All these following parameters are described below:

$search (mandatory) - This parameter is a mandatory parameter that can have both string
and array type values. The $search parameter contains the value which is going to be
searched for the replacement in the $string.

43
Reference : (1) www.javatpoint.com (2) www.w3schools.com

$replace (mandatory) - This parameter is a mandatory parameter which is replaced with


the search values. In simple words - this parameter holds that value which will replace the
$search value in the $string.

$string (mandatory) - This parameter is also a mandatory parameter which is an array or


string in which search and replace value is searched and replaced. It is the string or array with
which we are working.

$count (optional ) - It is the last and optional parameter. It is an integer variable which
counts the number of replacements done in the string. Simply, this variable stores the total
number of replacement performed on a string $string.

Return Values

This function returns an array or a string with the replaced values which is based on the
$string parameter.

Important Technical Details


Return It returns a string or an array with the replaced values.
values

Supported PHP 4 and above versions support this function.


PHP version

Changelog The $count parameter was included in PHP 5.0


This function experienced many trouble while using both $search and
$replace parameters as an array before PHP 4.3.3. So, that empty $search
indexes to be skipped without advancing the internal pointer on the
$replace array. Newer versions have resolved this problem.
After PHP 4.0.5, most of the parameters can now be an array.

Example

There is the practical implementation of the str_replace() function.

Example 1: Basic example with string variable

<?php
$string = "Hii everyone!";
$search = 'Hii';
$replace = 'Hello';
echo '<b>'."String before replacement:".'</br></b>';
echo $string.'</br>';
$newstr = str_replace($search, $replace, $string, $count);
echo '<b>'."New replaced string is:".'</br></b>';
echo $newstr.'</br>';
echo 'Number of replacement ='.$count;
?>

44
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Output:

In the above example, we can see that "Hii" is replaced with "Hello" and the number of
replacement is only 1.

Note: We can pass the $search and $replace value directly in the str_replace()
function.

Example 2: Replacement with array variable

To replace the multiple values in the $string, we have to take an array to store these values
for replacement.

<?php
$string = "Hii everyone! welcome to javaTpoint website. We will get
best technical content here.";
$search = array("Hii", "We");
$replace = array("Hello", "You");
echo '<b>'."String before replacement:".'</br></b>';
echo $string.'</br>';
$newstr = str_replace($search, $replace, $string, $count);
echo '<b>'."New replaced string is:".'</br></b>';
echo $newstr.'</br>';
echo 'Number of replacement ='.$count;
?>

Output:

In this output, we can see that "Hii" is replaced with "Hello" and "We" is replaced with
"You" and the number of replacement is 2.

45
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Array Sorting Function


we will go through the following PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key
(1) Sort Array in Ascending Order - sort()

The sort() function sorts an indexed array in ascending order.

Syntax
sort(array, sorttype)

Parameter Values

Parameter Description

Array Required. Specifies the array to sort

Sorttype Optional. Specifies how to compare the array elements/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 on
current locale
 4 = SORT_NATURAL - Compare items as strings using natural
ordering
 5 = SORT_FLAG_CASE -

The following example sorts the elements of the $cars array in ascending alphabetical order:

46
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Example
<?php
$cars= array("Volvo", "BMW", "Toyota");
sort($cars);
?>

BMW
Toyota
Volvo

The following example sorts the elements of the $numbers array in ascending numerical
order:

Example
<?php
$numbers= array(4, 6, 2, 22, 11);
sort($numbers);
?>

Output:
2
4
6
11
22
(2) Sort Array in Descending Order - rsort()

The rsort() function sorts an indexed array in descending order.

Syntax
rsort(array, sorttype)

Parameter Values

Parameter Description

Array Required. Specifies the array to sort

Sorttype Optional. Specifies how to compare the array elements/items. Possible


values:

47
Reference : (1) www.javatpoint.com (2) www.w3schools.com

 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 on
current locale
 4 = SORT_NATURAL - Compare items as strings using natural
ordering
 5 = SORT_FLAG_CASE -

The following example sorts the elements of the $cars array in descending alphabetical order:

Example
<?php
$cars= array("Volvo", "BMW", "Toyota");
rsort($cars);
?>

Volvo
Toyota
BMW

The following example sorts the elements of the $numbers array in descending numerical
order:

Example
<?php
$numbers= array(4, 6, 2, 22, 11);
rsort($numbers);
?>

Output:
22
11
6
4
2

(3) Sort Array (Ascending Order), According to Value - asort()

The asort() function sorts an associative array in ascending order, according to the value.

48
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Syntax
asort(array, sorttype)

The following example sorts an associative array in ascending order, according to the value:

Example
<?php
$age= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>

Key=Peter,Value=35
Key=Ben,Value=37
Key=Joe, Value=43

(4) Sort Array (Ascending Order), According to Value - arsort()

The arsort() function sorts an associative array in descending order, according to the value.

Syntax
arsort(array, sorttype)

The following example sorts an associative array in descending order, according to the value:

Example

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

Outout:
Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35

(5) Sort Array (Ascending Order), According to Key - ksort()

The ksort() function sorts an associative array in ascending order, according to the key.

Syntax
ksort(array, sorttype)

The following example sorts an associative array in ascending order, according to the key:

49
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Example
<?php
$age= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>

Output:
Key=Ben,Value=37
Key=Joe,Value=43
Key=Peter, Value=35

(6) Sort Array (Ascending Order), According to Key - krsort()

The krsort() function sorts an associative array in descending order, according to the key.

Syntax
krsort(array, sorttype)

The following example sorts an associative array in descending order, according to the key:

Example

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

Outout
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37

(7) PHP count() Function

The count() function returns the number of elements in an array.

Syntax
count(array, mode)

Parameter Values

Parameter Description

50
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Array Required. Specifies the array

Mode Optional. Specifies the mode. Possible values:

 0 - Default. Does not count all elements of multidimensional arrays


 1 - Counts the array recursively (counts all the elements of
multidimensional arrays)

Example

Return the number of elements in an array:

<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>

Output
3

(8) PHP current() Function

The current() function returns the value of the current element in an array.

Every array has an internal pointer to its "current" element, which is initialized to the first
element inserted into the array.

Tip: This function does not move the arrays internal pointer.

Syntax
current(array)

Parameter Values

Parameter Description

Array Required. Specifies the array to use

51
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Example

Output the value of the current element in an array:

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

echo current($people) . "<br>";


?>

output
Peter

(9) PHP prev() Function

The prev() function moves the internal pointer to, and outputs, the previous element in the
array.

Syntax
prev(array)

Parameter Values

Parameter Description

Array Required. Specifies the array to use

Example

Output the value of the current, next and previous element in the array:

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

echo current($people) . "<br>";


echo next($people) . "<br>";
echo prev($people);
?>

Output:
Peter
Joe
Peter

52
Reference : (1) www.javatpoint.com (2) www.w3schools.com

(10) PHP next() Function

The next() function moves the internal pointer to, and outputs, the next element in the array.

Syntax
next(array)

Parameter Values

Parameter Description

Array Required. Specifies the array to use

Example

Output the value of the current and the next element in the array:

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

echo current($people) . "<br>";


echo next($people);
?>

Output:
Peter
Joe

(11) PHP list() Function

The list() function is used to assign values to a list of variables in one operation.

Note: Prior to PHP 7.1, this function only worked on numerical arrays.

Syntax
list(var1, var2, ...)

Parameter Values

Parameter Description

53
Reference : (1) www.javatpoint.com (2) www.w3schools.com

var1 Required. The first variable to assign a value to

var2,... Optional. More variables to assign values to

Example

Assign variables as if they were an array:

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

list($a, $b, $c) = $my_array;


echo "I have several animals, a $a, a $b and a $c.";
?>

Output:

I have several animals, a Dog, a Cat and a Horse.

(12) PHP in_array() Function

The in_array() function searches an array for a specific value.

Note: If the search parameter is a string and the type parameter is set to TRUE, the search is
case-sensitive.

Syntax
in_array(search, array, type)

Parameter Values

Parameter Description

Search Required. Specifies the what to search for

Array Required. Specifies the array to search

54
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Type Optional. If this parameter is set to TRUE, the in_array() function searches for
the search-string and specific type in the array.

Example

Search for the value "Glenn" in an array and output some text:

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

if (in_array("Glenn", $people))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>

Output:

Match found

(13) PHP end() Function

The end() function moves the internal pointer to, and outputs, the last element in the array.

Syntax
end(array)

Parameter Values

Parameter Description

Array Required. Specifies the array to use

55
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Example

Output the value of the current and the last element in an array:

<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
echo current($people) . "<br>";
echo end($people);
?>

Output:
Peter
Cleveland

(14) PHP each() Function

The each() function returns the current element key and value, and moves the internal pointer
forward.

Note: The each() function is deprecated in PHP 7.2.

This element key and value is returned in an array with four elements. Two elements (1 and
Value) for the element value, and two elements (0 and Key) for the element key.

Syntax
each(array)

Parameter Values

Parameter Description

Array Required. Specifies the array to use

Example

Return the current element key and value, and move the internal pointer forward:

<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
print_r (each($people));
?>

Output:
Array ( [1] => Peter [value] => Peter [0] => 0 [key] => 0 )

56
Reference : (1) www.javatpoint.com (2) www.w3schools.com

(15) PHP array_chunk() Function

The array_chunk() function splits an array into chunks of new arrays.

Syntax
array_chunk(array, size, preserve_key)

Parameter Values

Parameter Description

Array Required. Specifies the array to use

Size Required. An integer that specifies the size of each chunk

preserve_key Optional. Possible values:

 true - Preserves the keys


 false - Default. Reindexes the chunk numerically

Split an array into chunks of two:

Example:

<?php
$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
print_r(array_chunk($cars,2));

?>

Output:

Array ( [0] => Array ( [0] => Volvo [1] => BMW ) [1] => Array ( [0] => Toyota [1] =>
Honda ) [2] => Array ( [0] => Mercedes [1] => Opel ) )

(16) PHP array_merge() Function

The array_merge() function merges one or more arrays into one array.

Tip: You can assign one array to the function, or as many as you like.

57
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Note: If two or more array elements have the same key, the last one overrides the others.

Note: If you assign only one array to the array_merge() function, and the keys are integers,
the function returns a new array with integer keys starting at 0 and increases by 1 for each
value (See example below).

Tip: The difference between this function and the array_merge_recursive() function is when
two or more array elements have the same key. Instead of override the keys, the
array_merge_recursive() function makes the value as an array.

Syntax
array_merge(array1, array2, array3, ...)

Parameter Values

Parameter Description

array1 Required. Specifies an array

array2 Optional. Specifies an array

array3,... Optional. Specifies an array

Merge two arrays into one array:

<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>

Output
Array ( [0] => red [1] => green [2] => blue [3] => yellow )

(17) PHP array_pop() Function

The array_pop() function deletes the last element of an array.

Syntax

58
Reference : (1) www.javatpoint.com (2) www.w3schools.com

array_pop(array)

Parameter Values

Parameter Description

Array Required. Specifies an array

Example

Delete the last element of an array:

<?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>

Output:
Array ( [0] => red [1] => green )

(18) PHP array_replace() Function

The array_replace() function replaces the values of the first array with the values from
following arrays.

Tip: You can assign one array to the function, or as many as you like.

If a key from array1 exists in array2, values from array1 will be replaced by the values from
array2. If the key only exists in array1, it will be left as it is (See Example 1 below).

If a key exist in array2 and not in array1, it will be created in array1 (See Example 2 below).

If multiple arrays are used, values from later arrays will overwrite the previous ones (See
Example 3 below).

Tip: Use array_replace_recursive() to replace the values of array1 with the values from
following arrays recursively.

Syntax
array_replace(array1, array2, array3, ...)

59
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Parameter Values

Parameter Description

array1 Required. Specifies an array

array2 Optional. Specifies an array which will replace the values of array1

array3,... Optional. Specifies more arrays to replace the values of array1 and array2,
etc. Values from later arrays will overwrite the previous ones.

Example:

Replace the values of the first array ($a1) with the values from the second array ($a2):

<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_replace($a1,$a2));
?>

Output:
Array ( [0] => blue [1] => yellow )

(19) PHP array_reverse() Function

The array_reverse() function returns an array in the reverse orde

Syntax

array_reverse(array, preserve)

Parameter Values

Parameter Description

Array Required. Specifies an array

60
Reference : (1) www.javatpoint.com (2) www.w3schools.com

preserve Optional. Specifies if the function should preserve the keys of the array or
not. Possible values:

 true
 false

Return an array in the reverse order:

<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>

Output
Array ( [c] => Toyota [b] => BMW [a] => Volvo )

(20) PHP array_search() Function

The array_search() function search an array for a value and returns the key.

Syntax
array_search(value, array, strict)

Parameter Values

Parameter Description

Value Required. Specifies the value to search for

Array Required. Specifies the array to search in

Strict Optional. If this parameter is set to TRUE, then this function will search for
identical elements in the array. Possible values:

 true
 false - Default

When set to true, the number 5 is not the same as the string 5

61
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Search an array for the value "red" and return its key:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>

Output:
a

62
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Date & Time Function


(1) PHP date() function
The date() function formats a local date and time, and returns the formatted date string.

Syntax
date(format, timestamp)

Parameter Values

Required. Specifies the format of the outputted date string. The following characters can be used:

 d - The day of the month (from 01 to 31)


 D - A textual representation of a day (three letters)
 j - The day of the month without leading zeros (1 to 31)
 l (lowercase 'L') - A full textual representation of a day
 N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
 S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works
well with j)
 w - A numeric representation of the day (0 for 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 a month (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 leap year, 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 Daylight Savings Time, 0
otherwise)
 O - Difference to Greenwich time (GMT) in hours (Example: +0100)

63
Reference : (1) www.javatpoint.com (2) www.w3schools.com

 P - Difference to Greenwich time (GMT) in hours:minutes (added in PHP 5.1.3)


 T - Timezone abbreviations (Examples: EST, MDT)
 Z - Timezone offset in seconds. The offset for 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)

Timestamp-

Optional. Specifies an integer Unix timestamp. Default is the current local time (time())

Example

Format a local date and time and return the formatted date strings:

<?php
// Prints the day
echo date("l") . "<br>";

// Prints the day, date, month, year, time, AM or PM


echo date("l jS \of F Y h:i:s A");
?>

Output:
Saturday
Saturday 22nd of August 2020 06:24:33 AM

(2) PHP getdate() Function

The getdate() function returns date/time information of a timestamp or the current local
date/time.

Syntax
getdate(timestamp)

Parameter Values

Parameter Description

64
Reference : (1) www.javatpoint.com (2) www.w3schools.com

timestamp Optional. Specifies an integer Unix timestamp.

Default is the current local time (time())

Example

Return date/time information of the current local date/time:

<?php
print_r(getdate());
?>

Output:

Array ( [seconds] => 17 [minutes] => 11 [hours] => 6 [mday] => 22 [wday] => 6 [mon] => 8
[year] => 2020 [yday] => 234 [weekday] => Saturday [month] => August [0] =>
1598076677 )

(3) PHP checkdate() Function

The checkdate() function is used to validate a Gregorian date.

Syntax
checkdate(month, day, year)

Parameter Values

Parameter Description

Month Required. Specifies the month as a number between 1 and 12

Day Required. Specifies the day as a number between 1 and 31

Year Required. Specifies the year as a number between 1 and 32767

65
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Example

Check if several dates are valid Gregorian dates:

<?php
var_dump(checkdate(12,31,-400));
echo "<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>

bool(false)
bool(false)
bool(true)

(4) PHP date_create() Function

The date_create() function returns a new DateTime object.

Syntax
date_create(time, timezone)

Parameter Values

Parameter Description

Time Optional. Specifies a date/time string. NULL indicates the current time

Timezone Optional. Specifies the timezone of time. Default is the current timezone.

Return a new DateTime object, and then format the date:

<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d");
?>

output

66
Reference : (1) www.javatpoint.com (2) www.w3schools.com

2013/03/15

(5) PHP date_format() Function

The date_format() function returns a date formatted according to the specified format.

Note: This function does not use locales (all output is in English).

Tip: Also look at the date() function, which formats a local date/time.

Syntax
date_format(object, format)

Parameter Values

Parameter Description

Object Required. Specifies a DateTime object returned by date_create()

Format Required. Specifies the format for the date. The following characters can be
used:

 d - The day of the month (from 01 to 31)


 D - A textual representation of a day (three letters)
 j - The day of the month without leading zeros (1 to 31)
 l (lowercase 'L') - A full textual representation of a day
 N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for
Sunday)
 S - The English ordinal suffix for the day of the month (2 characters st,
nd, rd or th. Works well with j)
 w - A numeric representation of the day (0 for 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 a month (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 leap year, 0 otherwise)
 o - The ISO-8601 year number

67
Reference : (1) www.javatpoint.com (2) www.w3schools.com

 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 Daylight
Savings Time, 0 otherwise)
 O - Difference to Greenwich time (GMT) in hours (Example: +0100)
 P - Difference to Greenwich time (GMT) in hours:minutes (added in
PHP 5.1.3)
 T - Timezone abbreviations (Examples: EST, MDT)
 Z - Timezone offset in seconds. The offset for 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)

Example

Return a new DateTime object, and then format the date:

<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>

Output:
2013/03/15 00:00:00

(6) PHP date_add() Function

The date_add() function adds some days, months, years, hours, minutes, and seconds to a
date.

Syntax

68
Reference : (1) www.javatpoint.com (2) www.w3schools.com

date_add(object, interval)

Parameter Values

Parameter Description

Object Required. Specifies a DateTime object returned by date_create()

Interval Required. Specifies a DateInterval object

<?php
$date=date_create("2013-03-15");
date_add($date,date_interval_create_from_date_string("40 days"));
echo date_format($date,"Y-m-d");
?>
Output :
2013-04-24

(7) PHP date_diff() Function

The date_diff() function returns the difference between two DateTime objects.

Syntax
date_diff(datetime1, datetime2, absolute)

Parameter Values

Parameter Description

datetime1 Required. Specifies a DateTime object

datetime2 Required. Specifies a DateTime object

69
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Absolute Optional. Specifies a Boolean value. TRUE indicates that the interval/difference
MUST be positive. Default is FALSE

Example

Calculate the difference between two dates:

<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");

?>

Output:
+272 days

(8) PHP date_default_timezone_get() Function

The date_default_timezone_get() function returns the default timezone used by all date/time
functions in the script.

Syntax
date_default_timezone_get()

Example

Return the default timezone:

<?php
echo date_default_timezone_get();
?>

Output:
UTC

(9) PHP date_default_timezone_set() Function

The date_default_timezone_set() function sets the default timezone used by all date/time
functions in the script.

70
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Syntax
date_default_timezone_set(timezone)

Parameter Values

Parameter Description

Timezone Required. Specifies the timezone to use, like "UTC" or "Europe/Paris". List of
valid timezones: http://www.php.net/manual/en/timezones.php

Example

Set the default timezone:

<?php
date_default_timezone_set("Asia/Bangkok");
echo date_default_timezone_get();
?>

Output:
Asia/Bangkok

(10) PHP time() Function

The time() function returns the current time in the number of seconds since the Unix Epoch
(January 1 1970 00:00:00 GMT).

Syntax
time()

Example

Return the current time as a Unix timestamp, then format it to a date:

<?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
?>

71
Reference : (1) www.javatpoint.com (2) www.w3schools.com

Output:
1598079460
2020-08-22

(11) PHP mktime() Function

The mktime() function returns the Unix timestamp for a date.

Tip: This function is identical to gmmktime() except the passed parameters represents a date
(not a GMT date).

Syntax
mktime(hour, minute, second, month, day, year, is_dst)

Parameter Values

Parameter Description

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

72
Reference : (1) www.javatpoint.com (2) www.w3schools.com

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 may cause unexpected results). Note: This parameter is removed in PHP 7.0. The
new timezone handling features should be used instead

Example

Return the Unix timestamp for a date. Then use it to find the day of that date:

<?php
// Prints: October 3, 1975 was on a Friday
echo "Oct 3, 1975 was on a ".date("l", mktime(0,0,0,10,3,1975));
?>

Output:

Oct 3, 1975 was on a Friday

73

You might also like