Web Technology Unit-3 Notes
CHAPTER 3- Built-in Functions
PHP contains hundreds of built-in functions, which can be used for different purpose. They are
categorized in the context of they are used.
Array Functions:
count( ) : The count() function returns the number of elements in an array.
Syntax:
count(array, mode)
Parameter Description
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 1:
<?php
$animals=array("Lion","Tiger","Elephant");
echo count($animals);
?>
Output:
3
Example 2:
<?php
$cars=array (
"Volvo"=>array ("XC60", "XC90"),
"BMW"=>array ("X3", "X5"),
"Toyota"=>array ("Highlander")
);
echo "Normal count: " . count($cars)."<br>";
echo "Recursive count: " . count($cars,1);
?>
Output:
Normal count: 3
Recursive count: 8
Web Technology Unit-3 Notes
sort( ) : Sort an array in ascending order
Syntax:
sort(array &$array, int $flags = SORT_REGULAR) : bool
The optional second parameter flags may be used to modify the sorting behavior using these values:
Sorting type flags:
SORT_REGULAR - compare items normally; the details are described in the comparison operators
section
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale,
which can be changed using setlocale()
SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL
to sort strings case-insensitively
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars,);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
Output:
BMW
Toyota
Volvo
Web Technology Unit-3 Notes
array_count_values( ) : Counts all the values of an array
Syntax:
array_count_values(array $array) : array
Example:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output:
Array( [1] => 2 [hello] => 2 [world] => 1)
array_key_exists( ) : Checks if the given key or index exists in the array
Syntax:
array_key_exists(string|int $key, array $array) : bool
Example:
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
?>
Output:
The 'first' element is in the array
array_push( ) : Push one or more elements onto the end of array
Syntax:
array_push(array &$array, mixed ...$values) : int
Web Technology Unit-3 Notes
Returns the new number of elements in the array.
Example:
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>
Output:
Array
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
array_search( ) : Searches the array for a given value and returns the first corresponding key if
successful
Syntax:
array_search(mixed $needle, array $haystack, bool $strict = false): int | string | false
Returns the key for needle if it is found in the array, false otherwise.
If needle is found in haystack more than once, the first matching key is returned. To return the keys
for all matching values, use array_keys() with the optional search_value parameter instead.
Example:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
Web Technology Unit-3 Notes
echo "'green' is at key: $key<br>";
$key = array_search('red', $array); // $key = 1;
echo "'red' is at key: $key";
?>
Output:
'green' is at key: 2
'red' is at key: 1
array_reverse( ) : Return an array with elements in reverse order
Syntax:
array_reverse(array $array, bool $preserve_keys = false): array
If preserve_keys set to true numeric keys are preserved. Non-numeric keys are not affected by this
setting and will always be preserved.
Example:
<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>
Output:
Array ( [c] => Toyota [b] => BMW [a] => Volvo )
array_unique( ) : Removes duplicate values from an array
Syntax:
array_unique(array $array, int $flags = SORT_STRING): array
The optional second parameter flags may be used to modify the sorting behavior using these values:
Sorting type flags:
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.
Web Technology Unit-3 Notes
Example:
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
//echo "<pre>";(USE THIS FOR OUTPUT 2)
$result = array_unique($input);
print_r($result);
?>
Output:1
Array ( [a] => green [0] => red [1] => blue )
array_values( ) : returns all the values from the array and indexes the array numerically
Syntax:
array_values(array $array): array
Example:
<?php
$array = array("size" => "XL", "color" =>
"gold");print_r(array_values($array));
?>
Output:
Array ( [0] => XL [1] => gold )
Web Technology Unit-3 Notes
in_array( ) : Checks if a value exists in an array
Syntax:
in_array(mixed $needle, array $haystack, bool $strict = false): bool
Example:
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
if (in_array("mac", $os)) {
echo "Got mac";
?>
Output:
Got Irix
array_walk( ) : Applies the user-defined function to each element of the array.
Syntax:
array_walk(array &$array, callable $callback, mixed $arg = null): bool
Example:
<?php
function myfunction($value,$key)
echo "The key $key has the value $value<br>";
}
Web Technology Unit-3 Notes
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction");
?>
Output:
The key a has the value red
The key b has the value green
The key c has the value blue
String Functions
explode( ) : Returns an array of strings, each of which is a substring of string formed by splitting it
on boundaries formed by the string separator.
Syntax:
explode(string $separator, string $string, int $limit = PHP_INT_MAX) : array
If limit is set and positive, the returned array will contain a maximum of limit elements with the last
element containing the rest of string.
If the limit parameter is negative, all components except the last -limit are returned.
If the limit parameter is zero, then this is treated as 1.
Example:
<?php
$str = "Hello world. Have a nice day.";
print_r (explode(" ",$str));
?>
Output:
Array ( [0] => Hello [1] => world. [2] => Have [3] => a [4] => nice[5] => day. )
Web Technology Unit-3 Notes
implode( ) : Returns a string containing a string representation of all the array elements in the
same order, with the separator string between each element.
Syntax:
implode(array $array, string $separator) : string
Example:
<?php
$arr = array('Hello','World!','nice','Day!');
echo implode(" ",$arr);
?>
Output:
Hello World! Nice Day!
trim ( ) : Strip whitespace (or other characters) from the beginning and end of a string
Syntax:
trim ( string $str [, string $charlist ] ) : string
Example:
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
Output:
Hello World!
llo Worl
md5 ( ) : Calculates the MD5 hash of string and returns that hash.
Syntax:
md5(string $string, bool $binary = false) : string
Example:
<?php
Web Technology Unit-3 Notes
$str = "Hello";
echo md5($str);
?>
Output:
8b1a9953c4611296a827abf8c47804d7
str_contains ( ) : Determine if a string contains a given substring
Syntax:
str_contains(string $haystack, string $needle) : bool
Example:
<?php
$string = 'The lazy fox jumped over the fence';
if (str_contains($string, 'lazy')) {
echo "The string 'lazy' was found in the string\n";
Output:
The string 'lazy' was found in the string
str_replace ( ) : Returns a string or an array with all occurrences of string in main string replaced
with the given string.
Syntax:
str_replace ( mixed $search , mixed $replace , mixed $subject) : mixed
Example:
<?php
echo str_replace("world","Ankit","Hello world!");
?>
Output:
Hello Ankit!
Web Technology Unit-3 Notes
str_split ( ) : Converts a string to an array
Syntax:
str_split(string $string, int $length = 1) : array
Example:
<?php
print_r(str_split("Hello"));
?>
Output:
Array ( [0] => H [1] => e [2] => l [3] => l [4] => o )
strcmp ( ) : Compare two strings (case-sensitive). Returns 0 if two strings are equal, <0 if string1
is less than string2 and >0 if string1 is greater than string2.
Syntax:
strcmp ( string $str1 , string $str2 ) : int
Example:
<?php
echo strcmp("Hello world!","Hello world!"); // the two strings are equal
echo <"br">;
echo strcmp("Hello world!","Hello"); // string1 is greater than string2
echo <"br">;
echo strcmp("Hello world!","Hello world! Hello!"); // string1 is less than string2
?>
Output:
0
-7
Web Technology Unit-3 Notes
strlen ( ) : Returns the length of the string passed.
Syntax:
strlen ( string $string) : int
Example:
<?php
$len = strlen("Hello WORLD!");
echo $len;
?>
Output:
12
strpos ( ) : Returns the position of the first occurrence of a string inside another string (case-
sensitive)
Syntax:
strpos ( string $haystack , mixed $needle) : mixed
Example:
<?php
echo strpos("I love php, I love php too!","php");
?>
Output:
7
strtolower ( ) : Returns $str with all alphabetic characters converted to lowercase.
Syntax:
strtolower ( string $string) : string
Example:
<?php
echo strtolower("Hello WORLD.");
?>
Output:
hello world
Web Technology Unit-3 Notes
strtoupper ( ) : Returns $str with all alphabetic characters converted to uppercase.
Syntax:
strtoupper (string $string) : string
Example:
<?php
echo strtoupper("Hello WORLD!");
?>
Output:
HELLO WORLD
Date and Time Functions
date( ) : Formats a local date/time.
Syntax:
date (string $format [, int $timestamp = time() ] ) : string
Returns a string formatted according to the given format string using the given integer timestamp or
the current time if no timestamp is given. In other words, timestamp is optional.
format 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 through 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 through 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)
Web Technology Unit-3 Notes
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)
e - The timezone identifier (Examples: UTC, 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)
T - Timezone setting of the PHP machine (Examples: EST, MDT)
Web Technology Unit-3 Notes
Z - Timezone offset in seconds. The offset west of UTC is negative, and the offset
east of UTC is positive (-43200 to 43200)
c - The ISO-8601 date (e.g. 2004-02-12T15:19:21+00:00)
r - The RFC 2822 formatted date (e.g. Thu, 21 Dec 2000 16:01:07 +0200)
U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
Optional. This is an integer Unix timestamp that defaults to the current local time if
timestamp
a timestamp is not given. In other words, it defaults to the value of time().
Example:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Output:
Today is 2024/01/06
Today is 2024.01.06
Today is 2024-01-06
Today is Sunday
checkdate( ) : Validate a Gregorian date
Syntax:
checkdate ( int $month , int $day , int $year ) : bool
Checks the validity of the date formed by the arguments. A date is considered valid if each parameter
is properly defined.
Example:
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>
Output:
bool(true)
bool(false)
Web Technology Unit-3 Notes
date_parse( ): Returns associative array with detailed info about given date/time
Syntax:
date_parse(string $datetime) : array
Example:
<?php
print_r(date_parse("2022-05-01 12:30:45.5"));
?>
Output:
Array ( [year] => 2022 [month] => 5 [day] => 1 [hour] => 12 [minute] => 30 [second] =>
45 [fraction] => 0.5 [warning_count] => 0 [warnings] => Array ( ) [error_count] => 0
[errors] => Array ( ) [is_localtime] => ))
getdate( ): Returns an array that contains date and time information for a Unix timestamp.
Syntax:
getdate ([ int $timestamp = time() ] ) : array
Returns an associative array containing the date information of the timestamp, or the current local
time if no timestamp is given.
Example:
<?php
$today = getdate();
print_r($today);
?>
Output:
Array
[seconds] => 40
[minutes] => 58
Web Technology Unit-3 Notes
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
time( ): Returns current Unix timestamp
Syntax:
time ( void ) : int
Example:
<?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
?>
Output:
1407124248
2014-08-03
mktime( ) : Returns the Unix timestamp for a date.
Syntax:
mktime(hour, minute, second, month, day, year, is_dst) : int | false
Web Technology Unit-3 Notes
Parameter Description
hour Optional. Specifies the hour
minute Optional. Specifies the minute
second Optional. Specifies the second
month Optional. Specifies the numerical month
day Optional. Specifies the day
year Optional. Specifies the year.
is_dst Optional. Parameters always represent a GMT date so is_dst doesn't influence
the result.
Example:
<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Last day in Feb 2000 is: %d\n", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
?>
Output:
Last day in Feb 2000 is: 29
Last day in Feb 2000 is: 29
File Functions
fopen ( ) : Opens file or URL
Syntax:
fopen(string $filename, string $mode, bool $use_include_path = false, resource $context = null):
resource | false
Web Technology Unit-3 Notes
mode Description
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file
to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; otherwise it has the same behavior as 'w'.
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist,
attempt to create it. In this mode, fseek() has no effect, writes are always appended.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not
exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are
always appended.
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the
file already exists, the fopen() call will fail by returning false and generating an error of
level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to
specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
'x+' Create and open for reading and writing; otherwise it has the same behavior as 'x'.
'c' Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither
truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The
file pointer is positioned on the beginning of the file. This may be useful if it's desired to
get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could
truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be
used after the lock is requested).
'c+' Open the file for reading and writing; otherwise it has the same behavior as 'c'.
'e' Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on
POSIX.1-2008 conform systems.
Example:
<?php
$handle = fopen("/home//file.txt", "r");
$handle = fopen("/home//file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:[email protected]/somefile.txt", "w");
?>
Web Technology Unit-3 Notes
fread ( ) : Binary-safe file read
Syntax:
fread(resource $stream, int $length): string|false
stream - A file system pointer resource that is typically created using fopen().
length - Up to length number of bytes read.
Example:
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
fwrite ( ) : Binary-safe file write
Syntax:
fwrite(resource $stream, string $data, ?int $length = null): int|false
fwrite() writes the contents of data to the file stream pointed to by stream.
Example:
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>
Output:
21
Web Technology Unit-3 Notes
fclose ( ) : Closes an open file pointer
Syntax:
fclose(resource $stream): bool
Example:
< ?php
$handle = fopen('somefile.txt', 'r');
fclose($handle);
?>
copy ( ) : Copies file
Syntax:
copy(string $from, string $to, ?resource $context = null): bool
Example:
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
?>
file_exists ( ) : Checks whether a file or directory exists
Syntax:
file_exists(string $filename): bool
Web Technology Unit-3 Notes
Example:
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
file_size ( ) : Gets file size
Syntax:
filesize(string $filename): int | false
Example:
<?php
// outputs e.g. somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
?>
mkdir ( ) : Makes directory
Syntax:
filesize(string $filename): int | false
Example:
<?php
// outputs e.g. somefile.txt: 1024 bytes
Web Technology Unit-3 Notes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
?>
rmdir ( ) : Removes directory
Syntax:
rmdir(string $directory, ?resource $context = null): bool
Example:
<?php
if (!is_dir('examples')) {
mkdir('examples');
rmdir('examples');
?>
unlink ( ) : Deletes a file
Syntax:
unlink(string $filename, ?resource $context = null): bool
Example:
<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);
unlink('test.html');
?>