PHP Unit 2 PDF
PHP Unit 2 PDF
com
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.
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
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
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
1
Reference : (1) www.javatpoint.com (2) www.w3schools.com
Output:
2
Reference : (1) www.javatpoint.com (2) www.w3schools.com
"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
3
Reference : (1) www.javatpoint.com (2) www.w3schools.com
Examples
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
Output:
Home |
PHP |
Java |
HTML
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
require 'filename';
Or
require ('filename');
Examples
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
Output:
Home |
PHP |
Java |
HTML
This is Main Page
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.
<?php
echo "HELLO";
//require welcome.php file
require("welcome.php");
5
Reference : (1) www.javatpoint.com (2) www.w3schools.com
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
PHP Functions
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.
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>
7
Reference : (1) www.javatpoint.com (2) www.w3schools.com
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>
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
<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 );
9
Reference : (1) www.javatpoint.com (2) www.w3schools.com
Original Value is 15
Original Value is 21
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>
10
Reference : (1) www.javatpoint.com (2) www.w3schools.com
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
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>
Hello
12
Reference : (1) www.javatpoint.com (2) www.w3schools.com
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
Syntax
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
Syntax
Example
<?php
echo (floor(3.3)."<br/>");// 3
echo (floor(7.333)."<br/>");// 7
echo (floor(-4.8)."<br/>");// -5
?>
Output:
3
7
-5
Syntax
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
The decbin() function converts decimal number into binary. It returns binary number as a
string.
Syntax
Example
<?php
echo (decbin(2)."<br/>");// 10
echo (decbin(10)."<br/>");// 1010
echo (decbin(22)."<br/>");// 10110
?>
Output:
10
1010
10110
The dechex() function converts decimal number into hexadecimal. It returns hexadecimal
representation of given number as a string.
Syntax
Output:
2
a
16
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
Output:
2
12
26
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
Example
<?php
$n1=10;
echo (base_convert($n1,10,2)."<br/>");// 1010
?>
Output:
1010
Syntax
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
Syntax:
max(array_values);
OR
max(value1,value2,value3,value4...);
Name Description Required/Optional
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:
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:
Output:
Syntax:
min(array_values);
or
min(value1,value2,value3...);
Parameter Description
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:
Output:
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:
Output:
19
Reference : (1) www.javatpoint.com (2) www.w3schools.com
Syntax:
number pow ( number $base , number $exp )
Parameter Description Required /Optional
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:
<?php
$num=pow(-4, 2);
echo "Your number is = pow (-4, 2)".'<br>';
echo "By using sqrt function Your number is : ".$num;
?>
Output:
<?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:
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
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
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
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
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
Example
<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str);
echo $str;
?>
Output:
5) strrev() function
The strrev() function returns reversed string.
Syntax
23
Reference : (1) www.javatpoint.com (2) www.w3schools.com
Example
<?php
$str="my name is Sonoo jaiswal";
$str=strrev($str);
echo $str;
?>
Output:
6) strlen() function
The strlen() function returns length of the string.
Syntax
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:
Syntax:
string addslashes (string $str );
24
Reference : (1) www.javatpoint.com (2) www.w3schools.com
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:
?>
Output:
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:
Syntax:
ltrim(string,charlist);
Example 1
<?php
$str = " Hello PHP!";
echo "Without ltrim() Function: " . $str;
echo "<br>";
echo "With ltrim() function : " . ltrim($str);
?>
Output:
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
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:
Example 2
<?php
$str = "Hello PHP!";
echo "Your string is: ".$str ."<br>";
echo "By using trim() function :".trim($str,"Hed!");
?>
Output:
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>";
Output:
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>";
Output:
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
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.
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:
Remark: Second string comparison has returned -6 because the first string is 6 characters
smaller than the second string, including whitespace.
PHP string strcasecmp() is predefine function. It is used to compare two given string. It is and
case-insensitive.
It returns:
Syntax:
strcasecmp(string1,string2);
Parameter Description Required/Optional
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
?>
Output:
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 ] );
This function will help us to find the numeric position of the first occurrence of needle in the
haystack string
32
Reference : (1) www.javatpoint.com (2) www.w3schools.com
Output:
Output:
33
Reference : (1) www.javatpoint.com (2) www.w3schools.com
?>
Output:
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 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.
$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
<?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:
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:
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-
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.
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:
<?php
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.
Example 7
<?php
37
Reference : (1) www.javatpoint.com (2) www.w3schools.com
}
else{
echo "Search string not Found";
}
?>
Output:
In the above example, strrpos() start searching from 4th position. It found search string at
12th position.
Syntax
The syntax for the PHP strstr() function is given below, which consists three parameters.
Parameters
$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.
Examples of strstr()
There are some examples given below that will help us to learn the practical use of this
function.
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
<?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:
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
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.
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.
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:
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:
Syntax
The syntax of the str_replace() function is given below, which has the following four
parameters.
This function follows some rules while working, which are given below:
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
$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.
Example
<?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.
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
Syntax
sort(array, sorttype)
Parameter Values
Parameter Description
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()
Syntax
rsort(array, sorttype)
Parameter Values
Parameter Description
47
Reference : (1) www.javatpoint.com (2) www.w3schools.com
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
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
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
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
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
Syntax
count(array, mode)
Parameter Values
Parameter Description
50
Reference : (1) www.javatpoint.com (2) www.w3schools.com
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Output
3
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
51
Reference : (1) www.javatpoint.com (2) www.w3schools.com
Example
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
output
Peter
The prev() function moves the internal pointer to, and outputs, the previous element in the
array.
Syntax
prev(array)
Parameter Values
Parameter Description
Example
Output the value of the current, next and previous element in the array:
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
Output:
Peter
Joe
Peter
52
Reference : (1) www.javatpoint.com (2) www.w3schools.com
The next() function moves the internal pointer to, and outputs, the next element in the array.
Syntax
next(array)
Parameter Values
Parameter Description
Example
Output the value of the current and the next element in the array:
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
Output:
Peter
Joe
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
Example
<?php
$my_array = array("Dog","Cat","Horse");
Output:
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
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
The end() function moves the internal pointer to, and outputs, the last element in the array.
Syntax
end(array)
Parameter Values
Parameter Description
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
The each() function returns the current element key and value, and moves the internal pointer
forward.
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
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
Syntax
array_chunk(array, size, preserve_key)
Parameter Values
Parameter Description
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 ) )
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
<?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 )
Syntax
58
Reference : (1) www.javatpoint.com (2) www.w3schools.com
array_pop(array)
Parameter Values
Parameter Description
Example
<?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
Output:
Array ( [0] => red [1] => green )
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
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 )
Syntax
array_reverse(array, preserve)
Parameter Values
Parameter Description
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
<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>
Output
Array ( [c] => Toyota [b] => BMW [a] => Volvo )
The array_search() function search an array for a value and returns the key.
Syntax
array_search(value, array, strict)
Parameter Values
Parameter Description
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
Syntax
date(format, timestamp)
Parameter Values
Required. Specifies the format of the outputted date string. The following characters can be used:
63
Reference : (1) www.javatpoint.com (2) www.w3schools.com
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>";
Output:
Saturday
Saturday 22nd of August 2020 06:24:33 AM
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
Example
<?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 )
Syntax
checkdate(month, day, year)
Parameter Values
Parameter Description
65
Reference : (1) www.javatpoint.com (2) www.w3schools.com
Example
<?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)
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.
<?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
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
Format Required. Specifies the format for the date. The following characters can be
used:
67
Reference : (1) www.javatpoint.com (2) www.w3schools.com
Example
<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>
Output:
2013/03/15 00:00:00
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
<?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
The date_diff() function returns the difference between two DateTime objects.
Syntax
date_diff(datetime1, datetime2, absolute)
Parameter Values
Parameter Description
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
<?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
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
<?php
echo date_default_timezone_get();
?>
Output:
UTC
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
<?php
date_default_timezone_set("Asia/Bangkok");
echo date_default_timezone_get();
?>
Output:
Asia/Bangkok
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
<?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
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
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:
73