PHP Functions
jigar makhija
Date Functions
Date, getdate, setdate, Checkdate, time, mktime
<?php
$time = time();
print("Current Timestamp: ".$time);
?>
<?php
$bool = checkdate(12, 12, 2005);
if($bool){
print("Given date is valid");
}else{
print("Given date is invalid");
}
?>
DATE
<?php
$date = date("D M d Y");
print("Date: ".$date);
?>
TIME
<?php
$timestamp = mktime();
print($timestamp);
?>
Setting and Getting Dates
<?php
//Creating a date
$date = new DateTime();
//Setting the date
date_date_set($date, 2019, 07, 17);
print("Date: ".date_format($date, "Y/m/d"));
?>
<?php
//Date string
$date_string = "25-09-1989";
//Creating a DateTime object
$date_time_Obj = date_create($date_string);
print("Original Date: ".date_format($date_time_Obj,
"Y/m/d"));
print("n");
//Setting the date
$date = date_date_set($date_time_Obj, 2015, 11, 25 );
print("Modified Date: ".date_format($date, "Y/m/d"));
<?php
//Creating a DateTime object
$date_time_Obj = date_create("25-09-1989");
//formatting the date/time object
$format = date_format($date_time_Obj, "y-d-
m");
print("Date in yy-dd-mm format: ".$format);
?>
<?php
$info = getdate();
print_r($info);
?>
Variable Function
Gettype, settype, isset, unset, strval, floatval, intval, print_r
$a = 3;
echo gettype($a) . "<br>";
$b = 3.2;
echo gettype($b) . "<br>";
$a = array("red", "green", "blue");
print_r($a);
echo "<br>";
$b = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
print_r($b);
<?php
$a = "32"; // string
settype($a, "integer"); // $a is now integer
$b = 32; // integer
settype($b, "string"); // $b is now string
$c = true; // boolean
settype($c, "integer"); // $c is now integer (1)
?>
$a = 0;
// True because $a is set
if (isset($a)) {
echo "Variable 'a' is set.<br>";
}
Variable Function
Gettype, settype, isset, unset, strval, floatval, intval, print_r
$a = "Hello world!";
echo "The value of variable 'a' before unset: " . $a . "<br>";
unset($a);
echo "The value of variable 'a' after unset: " . $a;
?>
$b = 3.2;
echo intval($b) . "<br>";
$c = "32.5";
echo intval($c) . "<br>";
$b = "1234.56789Hello";
echo floatval($b) . "<br>";
$c = "Hello1234.56789";
echo floatval($c) . "<br>";
$a = "1234.56789";
echo doubleval($a) .
"<br>";
$b = "1234.56789Hello";
echo doubleval($b) .
"<br>";
$d = "Hello1234.56789";
echo strval($d) . "<br>";
$e = 1234;
echo strval($e) . "<br>";
String Function
Chr, ord, strtolower, strtoupper, strlen, ltrim, rtrim trim, substr, strcmp,
strcasecmp, strops,strrpos, strstr, stristr, str_replace, strrev, echo, print
• echo():Outputs one or more strings
• print():Outputs one or more strings
• Chr(): Returns a character from a specified ASCII value
• ord():Returns the ASCII value of the first character of a string
• strtolower(): Converts a string to lowercase letters
• strtoupper():Converts a string to uppercase letters
• strlen():Returns the length of a string
• rtrim ():Removes whitespace or other characters from the right
side of a string
• ltrim():Removes whitespace or other characters from the left
side of a string
• trim():Removes whitespace or other characters from both sides of a string
String Function
Chr, ord, strtolower, strtoupper, strlen, ltrim, rtrim trim, substr, strcmp,
strcasecmp, strops,strrpos, strstr, stristr, str_replace, strrev, echo, print
– strcmp():Compares two strings (case-sensitive)
– strcasecmp():Compares two strings (case-insensitive)
– strpos():Returns the position of the first occurrence of a string inside
another string (case-sensitive)
– strrpos():Finds the position of the last occurrence of a string inside
another string (case-sensitive)
– strstr():Finds the first occurrence of a string inside another string
(case-sensitive)
– stristr():Finds the first occurrence of a string inside another string
(case-insensitive)
– str_replace():Replaces some characters in a string (case-sensitive)
– strrev():Reverses a string
Math Function
Abs, ceil, floor, round, fmod, min, max, pow, sqrt, rand
<?php
echo (abs(-7)."<br/>"); // 7
(integer)
echo (abs(7)."<br/>"); //7 (integer)
echo (abs(-7.2)."<br/>"); //7.2
(float/double)
?>
<?php
echo (ceil(3.3)."<br/>");// 4
echo (ceil(7.333)."<br/>");// 8
echo (ceil(-4.8)."<br/>");// -4
?>
<?php
echo (floor(3.3)."<br/>");// 3
echo (floor(7.333)."<br/>");//
7
echo (floor(-4.8)."<br/>");// -5
?>
<?php
echo (sqrt(16)."<br/>");// 4
echo (sqrt(25)."<br/>");// 5
echo (sqrt(7)."<br/>");//
2.6457513110646
?>
<?php
$num=pow(3, 2);
echo $num;
?>
echo "using round() function : ".(round(3.96754,2)); echo "Random number b/w 10-100:
".(rand(10,100));
$x = 5.7;
$y = 1.3;
echo "Your Given Nos is : x=5.7, y=1.3";
echo "<br>"."By using 'fmod()' function your
value is:".fmod($x, $y);
$num=min(4,14,3,5,14.2); $num=max(4,14,3,5,14.2);
User Define Function
argument function, default argument, variable function, return
function
function functionname(){
//code to be executed
}
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
function sayHello($name,$age){
echo "Hello $name, you are $age years
old<br/>";
}
sayHello("Sonoo",27);
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
function
sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is:
".cube(3);
//RECURSIVE FUNCTIONS
<?php
function display($number) {
if($number<=5){
echo "$number <br/>";
display($number+1);
}
}
display(1);
Variable Length Argument Function:
func_num_args, func_get_arg, func_get_args
function combined() {
$num_arg = func_num_args();
echo "Number of arguments: " .$num_arg . "n";
}
combined('A', 'B', 'C');
<?php
function printValue($value) {
// Update value variable
$value = "The value is: " . $value;
// Print the value of the first argument
echo func_get_arg(0);
}
// Run function
printValue(123);
?>
<?php
function combined() {
$num_arg = func_num_args();
if($num_arg > 0) {
$arg_list = func_get_args();
for ($i = 0; $i < $num_arg; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "n";
}
}
}
combined('A', 'B', 'C');
?>
Count, list, in_array, current, next, previous, end, each, sort, rsort,
asort,
arsort, array_merge, array_reverse
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
print($result);
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport);
print "$mode <br />";
$mode = next($transport);
print "$mode <br />";
$mode = current($transport);
print "$mode <br />";
$mode = prev($transport);
print "$mode <br />";
$mode = end($transport);
print "$mode <br />";
$mode = current($transport);
print "$mode <br />";
$transport = array('foot', 'bike',
'car', 'plane');
$key_value = each($transport);
print_r($key_value);
print "<br />";
$key_value = each($transport);
print_r($key_value);
print "<br />";
$key_value = each($transport);
print_r($key_value);
$fruit = array("mango","apple","banana");
list($a, $b, $c) = $fruit;
echo "I have several fruits, a $a, a $b, and
a $c.";
$input =
array("a"=>"banan
a","b"=>"mango","c
"=>"orange");
print_r(array_rever
se($input));
Count, list, in_array, current, next, previous, end, each, sort, rsort,
asort,
arsort, array_merge, array_reverse
$mobile_os = array("Mac", "android", "java",
"Linux");
if (in_array("java", $mobile_os)) {
echo "Got java";
}
<?php
$input = array("d"=>"lemon", "a"=>"orange", "b"=>"banana"
);
rsort($input);
print_r($input);
?>
<?php
$input = array("d"=>"lemon", "a"=>"orange",
"b"=>"banana" );
sort($input);
print_r($input);
?>
<?php
$fruits = array("d"=>"lemon", "a"=>"orange",
"b"=>"banana" );
arsort($fruits);
print_r($fruits);
?>
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana"
);
asort($fruits);
print_r($fruits);
?>
$input =
array("a"=>"Horse","b"=>"Cat","c"=>"Dog");
$input1 =
array("d"=>"Cow","a"=>"Cat","e"=>"elephant");
print_r(array_merge($input,$input1));
Miscellaneous Function
define, constant, include, require, header, die
<?php
define("GREETING","Hello you! How are you today?");
echo constant("GREETING");
?>
<?php
$site = "https://www.w3schools.com/";
fopen($site,"r")
or die("Unable to connect to $site");
?>
<?php
include("menu.html"); ?>
<?php
require("menu.html"); ?>
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.
define() function to create a constant.
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>
define("MESSAGE","Hello JavaTpoint PHP",true);//not
case sensitive
The header() is a pre-defined network function of PHP, which sends a raw HTTP header to a client.
void header (string $header, boolean $replace = TRUE, int $http_response_code)
File handling Function:
fopen, fread, fwrite, fclose, file_exists, is_readable, is_writable, fgets, fgetc, file, file_get_contents,
filejutcontents, ftell, fseek, rewind, copy, unlink, rename, move upload file
<?php
$handle = fopen("c:folderfile.txt", "r");
?>
<?php
fclose($handle);
?>
<?php
$filename = "c:myfile.txt";
$handle = fopen($filename, "r");//open file in read
mode
$contents = fread($handle,
filesize($filename));//read file
echo $contents;//printing data of file
fclose($handle);//close file
?>
<?php
$fp = fopen('data.txt', 'w');//open file in write mode
fwrite($fp, 'hello ');
fwrite($fp, 'php file');
fclose($fp);
echo "File written successfully";
?>
fread(file_pointer, length)
echo fread($file_pointer, "7");
echo fgets($file);
if (file_exists($file_pointer)) {
echo "The file $file_pointer exists";
}
if (is_readable($myfile))
{
echo '$myfile is readable';
}
File handling Function:
fopen, fread, fwrite, fclose, file_exists, is_readable, is_writable, fgets, fgetc, file, file_get_contents,
filejutcontents, ftell, fseek, rewind, copy, unlink, rename, move upload file
$myfile = fopen("gfg.txt", "w");
echo fwrite($myfile, "Hello!");
fclose($myfile);
$myfile = fopen("gfg.txt", "r");
echo ftell($myfile);
fseek($myfile, "36");
echo ftell($myfile);
$myfile = fopen("gfg.txt", "r+");
fwrite($myfile, 'geeksforgeeks');
rewind($myfile);
fwrite($myfile, 'portal');
rewind($myfile);
echo fread($myfile, filesize("gfg.txt"));
fclose($myfile);
$srcfile = '/user01/Desktop/admin/gfg.txt';
$destfile = 'user01/Desktop/admin/geeksforgeeks.txt';
echo copy($srcfile, $destfilefile);
rename( $old_name, $new_name) ;
unlink('data.txt');
echo "File deleted successfully";
// file is opened using fopen() function
$my_file = fopen("gfg.txt", "rw");
// Prints a single character from the
// opened file pointer
echo fgetc($my_file);

Php functions

  • 1.
  • 2.
    Date Functions Date, getdate,setdate, Checkdate, time, mktime <?php $time = time(); print("Current Timestamp: ".$time); ?> <?php $bool = checkdate(12, 12, 2005); if($bool){ print("Given date is valid"); }else{ print("Given date is invalid"); } ?> DATE <?php $date = date("D M d Y"); print("Date: ".$date); ?> TIME <?php $timestamp = mktime(); print($timestamp); ?>
  • 3.
    Setting and GettingDates <?php //Creating a date $date = new DateTime(); //Setting the date date_date_set($date, 2019, 07, 17); print("Date: ".date_format($date, "Y/m/d")); ?> <?php //Date string $date_string = "25-09-1989"; //Creating a DateTime object $date_time_Obj = date_create($date_string); print("Original Date: ".date_format($date_time_Obj, "Y/m/d")); print("n"); //Setting the date $date = date_date_set($date_time_Obj, 2015, 11, 25 ); print("Modified Date: ".date_format($date, "Y/m/d")); <?php //Creating a DateTime object $date_time_Obj = date_create("25-09-1989"); //formatting the date/time object $format = date_format($date_time_Obj, "y-d- m"); print("Date in yy-dd-mm format: ".$format); ?> <?php $info = getdate(); print_r($info); ?>
  • 4.
    Variable Function Gettype, settype,isset, unset, strval, floatval, intval, print_r $a = 3; echo gettype($a) . "<br>"; $b = 3.2; echo gettype($b) . "<br>"; $a = array("red", "green", "blue"); print_r($a); echo "<br>"; $b = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); print_r($b); <?php $a = "32"; // string settype($a, "integer"); // $a is now integer $b = 32; // integer settype($b, "string"); // $b is now string $c = true; // boolean settype($c, "integer"); // $c is now integer (1) ?> $a = 0; // True because $a is set if (isset($a)) { echo "Variable 'a' is set.<br>"; }
  • 5.
    Variable Function Gettype, settype,isset, unset, strval, floatval, intval, print_r $a = "Hello world!"; echo "The value of variable 'a' before unset: " . $a . "<br>"; unset($a); echo "The value of variable 'a' after unset: " . $a; ?> $b = 3.2; echo intval($b) . "<br>"; $c = "32.5"; echo intval($c) . "<br>"; $b = "1234.56789Hello"; echo floatval($b) . "<br>"; $c = "Hello1234.56789"; echo floatval($c) . "<br>"; $a = "1234.56789"; echo doubleval($a) . "<br>"; $b = "1234.56789Hello"; echo doubleval($b) . "<br>"; $d = "Hello1234.56789"; echo strval($d) . "<br>"; $e = 1234; echo strval($e) . "<br>";
  • 6.
    String Function Chr, ord,strtolower, strtoupper, strlen, ltrim, rtrim trim, substr, strcmp, strcasecmp, strops,strrpos, strstr, stristr, str_replace, strrev, echo, print • echo():Outputs one or more strings • print():Outputs one or more strings • Chr(): Returns a character from a specified ASCII value • ord():Returns the ASCII value of the first character of a string • strtolower(): Converts a string to lowercase letters • strtoupper():Converts a string to uppercase letters • strlen():Returns the length of a string • rtrim ():Removes whitespace or other characters from the right side of a string • ltrim():Removes whitespace or other characters from the left side of a string • trim():Removes whitespace or other characters from both sides of a string
  • 7.
    String Function Chr, ord,strtolower, strtoupper, strlen, ltrim, rtrim trim, substr, strcmp, strcasecmp, strops,strrpos, strstr, stristr, str_replace, strrev, echo, print – strcmp():Compares two strings (case-sensitive) – strcasecmp():Compares two strings (case-insensitive) – strpos():Returns the position of the first occurrence of a string inside another string (case-sensitive) – strrpos():Finds the position of the last occurrence of a string inside another string (case-sensitive) – strstr():Finds the first occurrence of a string inside another string (case-sensitive) – stristr():Finds the first occurrence of a string inside another string (case-insensitive) – str_replace():Replaces some characters in a string (case-sensitive) – strrev():Reverses a string
  • 8.
    Math Function Abs, ceil,floor, round, fmod, min, max, pow, sqrt, rand <?php echo (abs(-7)."<br/>"); // 7 (integer) echo (abs(7)."<br/>"); //7 (integer) echo (abs(-7.2)."<br/>"); //7.2 (float/double) ?> <?php echo (ceil(3.3)."<br/>");// 4 echo (ceil(7.333)."<br/>");// 8 echo (ceil(-4.8)."<br/>");// -4 ?> <?php echo (floor(3.3)."<br/>");// 3 echo (floor(7.333)."<br/>");// 7 echo (floor(-4.8)."<br/>");// -5 ?> <?php echo (sqrt(16)."<br/>");// 4 echo (sqrt(25)."<br/>");// 5 echo (sqrt(7)."<br/>");// 2.6457513110646 ?> <?php $num=pow(3, 2); echo $num; ?> echo "using round() function : ".(round(3.96754,2)); echo "Random number b/w 10-100: ".(rand(10,100)); $x = 5.7; $y = 1.3; echo "Your Given Nos is : x=5.7, y=1.3"; echo "<br>"."By using 'fmod()' function your value is:".fmod($x, $y); $num=min(4,14,3,5,14.2); $num=max(4,14,3,5,14.2);
  • 9.
    User Define Function argumentfunction, default argument, variable function, return function function functionname(){ //code to be executed } <?php function sayHello(){ echo "Hello PHP Function"; } sayHello();//calling function ?> function sayHello($name){ echo "Hello $name<br/>"; } sayHello("Sonoo"); function sayHello($name,$age){ echo "Hello $name, you are $age years old<br/>"; } sayHello("Sonoo",27); function adder(&$str2) { $str2 .= 'Call By Reference'; } $str = 'Hello '; adder($str); echo $str; function sayHello($name="Sonoo"){ echo "Hello $name<br/>"; } sayHello("Rajesh"); sayHello(); function cube($n){ return $n*$n*$n; } echo "Cube of 3 is: ".cube(3); //RECURSIVE FUNCTIONS <?php function display($number) { if($number<=5){ echo "$number <br/>"; display($number+1); } } display(1);
  • 10.
    Variable Length ArgumentFunction: func_num_args, func_get_arg, func_get_args function combined() { $num_arg = func_num_args(); echo "Number of arguments: " .$num_arg . "n"; } combined('A', 'B', 'C'); <?php function printValue($value) { // Update value variable $value = "The value is: " . $value; // Print the value of the first argument echo func_get_arg(0); } // Run function printValue(123); ?> <?php function combined() { $num_arg = func_num_args(); if($num_arg > 0) { $arg_list = func_get_args(); for ($i = 0; $i < $num_arg; $i++) { echo "Argument $i is: " . $arg_list[$i] . "n"; } } } combined('A', 'B', 'C'); ?>
  • 11.
    Count, list, in_array,current, next, previous, end, each, sort, rsort, asort, arsort, array_merge, array_reverse $a[0] = 1; $a[1] = 3; $a[2] = 5; $result = count($a); print($result); $transport = array('foot', 'bike', 'car', 'plane'); $mode = current($transport); print "$mode <br />"; $mode = next($transport); print "$mode <br />"; $mode = current($transport); print "$mode <br />"; $mode = prev($transport); print "$mode <br />"; $mode = end($transport); print "$mode <br />"; $mode = current($transport); print "$mode <br />"; $transport = array('foot', 'bike', 'car', 'plane'); $key_value = each($transport); print_r($key_value); print "<br />"; $key_value = each($transport); print_r($key_value); print "<br />"; $key_value = each($transport); print_r($key_value); $fruit = array("mango","apple","banana"); list($a, $b, $c) = $fruit; echo "I have several fruits, a $a, a $b, and a $c."; $input = array("a"=>"banan a","b"=>"mango","c "=>"orange"); print_r(array_rever se($input));
  • 12.
    Count, list, in_array,current, next, previous, end, each, sort, rsort, asort, arsort, array_merge, array_reverse $mobile_os = array("Mac", "android", "java", "Linux"); if (in_array("java", $mobile_os)) { echo "Got java"; } <?php $input = array("d"=>"lemon", "a"=>"orange", "b"=>"banana" ); rsort($input); print_r($input); ?> <?php $input = array("d"=>"lemon", "a"=>"orange", "b"=>"banana" ); sort($input); print_r($input); ?> <?php $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana" ); arsort($fruits); print_r($fruits); ?> <?php $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana" ); asort($fruits); print_r($fruits); ?> $input = array("a"=>"Horse","b"=>"Cat","c"=>"Dog"); $input1 = array("d"=>"Cow","a"=>"Cat","e"=>"elephant"); print_r(array_merge($input,$input1));
  • 13.
    Miscellaneous Function define, constant,include, require, header, die <?php define("GREETING","Hello you! How are you today?"); echo constant("GREETING"); ?> <?php $site = "https://www.w3schools.com/"; fopen($site,"r") or die("Unable to connect to $site"); ?> <?php include("menu.html"); ?> <?php require("menu.html"); ?> 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. define() function to create a constant. <?php define("MESSAGE","Hello JavaTpoint PHP"); echo MESSAGE; ?> define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive The header() is a pre-defined network function of PHP, which sends a raw HTTP header to a client. void header (string $header, boolean $replace = TRUE, int $http_response_code)
  • 14.
    File handling Function: fopen,fread, fwrite, fclose, file_exists, is_readable, is_writable, fgets, fgetc, file, file_get_contents, filejutcontents, ftell, fseek, rewind, copy, unlink, rename, move upload file <?php $handle = fopen("c:folderfile.txt", "r"); ?> <?php fclose($handle); ?> <?php $filename = "c:myfile.txt"; $handle = fopen($filename, "r");//open file in read mode $contents = fread($handle, filesize($filename));//read file echo $contents;//printing data of file fclose($handle);//close file ?> <?php $fp = fopen('data.txt', 'w');//open file in write mode fwrite($fp, 'hello '); fwrite($fp, 'php file'); fclose($fp); echo "File written successfully"; ?> fread(file_pointer, length) echo fread($file_pointer, "7"); echo fgets($file); if (file_exists($file_pointer)) { echo "The file $file_pointer exists"; } if (is_readable($myfile)) { echo '$myfile is readable'; }
  • 15.
    File handling Function: fopen,fread, fwrite, fclose, file_exists, is_readable, is_writable, fgets, fgetc, file, file_get_contents, filejutcontents, ftell, fseek, rewind, copy, unlink, rename, move upload file $myfile = fopen("gfg.txt", "w"); echo fwrite($myfile, "Hello!"); fclose($myfile); $myfile = fopen("gfg.txt", "r"); echo ftell($myfile); fseek($myfile, "36"); echo ftell($myfile); $myfile = fopen("gfg.txt", "r+"); fwrite($myfile, 'geeksforgeeks'); rewind($myfile); fwrite($myfile, 'portal'); rewind($myfile); echo fread($myfile, filesize("gfg.txt")); fclose($myfile); $srcfile = '/user01/Desktop/admin/gfg.txt'; $destfile = 'user01/Desktop/admin/geeksforgeeks.txt'; echo copy($srcfile, $destfilefile); rename( $old_name, $new_name) ; unlink('data.txt'); echo "File deleted successfully"; // file is opened using fopen() function $my_file = fopen("gfg.txt", "rw"); // Prints a single character from the // opened file pointer echo fgetc($my_file);