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

Unit-1

The document provides various examples of PHP operators, control structures, and functions, including arithmetic, assignment, comparison, conditional, logical operators, and loops. It also covers arrays, user-defined functions, variable scope, and built-in functions for handling variables and arrays. Each section includes code snippets demonstrating the usage of these concepts in PHP.

Uploaded by

yuvrajdhakan5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit-1

The document provides various examples of PHP operators, control structures, and functions, including arithmetic, assignment, comparison, conditional, logical operators, and loops. It also covers arrays, user-defined functions, variable scope, and built-in functions for handling variables and arrays. Each section includes code snippets demonstrating the usage of these concepts in PHP.

Uploaded by

yuvrajdhakan5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

 Example : Arithmetic Operator

<?php
$a=20;
$b=10;

$c = $a + $b;
echo "Addition is $c";

$c = $a - $b;
echo "<br>Substraction is ".$c;

$c = $a * $b;
echo "<br>Multiplication is ".$c;

$c = $a / $b;
echo "<br>Division is ".$c;

$c = $a % $b;
echo "<br>Moduls is ".$c;
?>
 Example : Assignment Operator
<?php

$a=20;

$b=40;

$c=10;

$d=20;

$e=10;

echo "Addition is ".$a += 20;


echo "<br>Substraction is ".$b -= 20;;

echo "<br>Multiplication is ".$c *= 10;

echo "<br>Division is ".$d /= 10;

echo "<br>Moduls is ".$e %= 5;

?>

 Example : Comparison Operator


<?php
$a=20;
$b=10;

if($a == $b)
{
echo "<br>Both are equal";
}
else
{
echo "<br>Both are not equal";
}

if($a < $b)


{
echo "<br>a is less than b";
}
else
{
echo "<br>a is greater than b";
}

if($a != $b)
{
echo "<br>a is not equal to b";
}
?>
 Example : Conditional Operator
<?php
$a=20;
$b=10;

($a>$b)? $c = "A is greater":$c="B is greater";


echo $c;

echo "<br>";
$s = "Rasmus ";
$nm = $s."Ledorf";
echo $nm;

?>

 Example : Logical Operator


<?php
$a=20;
$b=10;
$c=30;

if($a>$b && $a>$c)


{
echo "<br>a is maximum";
}
else if($b>$a and $b>$c)
{
echo "<br>b is maximum";
}

else
{
echo "<br>c is maximum";
}

if($a>$b || $a>$c)
{
echo "<br>This statement executed if at least one expression true";
}
?>
 Example : Simple If
<?php
$a=20;
echo "Good Afternoon";
if($a==20)
{
echo "<br>Hava a nice day";
}
echo "<br>Thanks for visit";

?>
 Example : If Else
<?php
$a=20;
echo "Good Afternoon";
if($a==20)
{
echo "<br>Hava a good day";
}
else
{
echo "<br>Hava a nice day";
}
echo "<br>Thanks for visit";
?>
 Example : If…ElseIf
<?php
$per=75;

if($per>=70)
{
echo "Distinction";
}
else if($per>=60)
{
echo "First Class";
}
else if($per>=50)
{
echo "Second Class";
}
else if($per>=40)
{
echo "Pass Class";
}
else
{
echo "Fail";
}
?>

 Example : Switch Case


<?php
$month=7;
switch($month)
{
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
case 7:
echo "Sunday";
break;
default:
echo "Invalid day";
}
?>
 Example : Break Statement
<?php
error_reporting(0);
for($i<=1;$i<=10;$i++)
{
if($i==5)
{
break;
}
else
{
echo $i;
}
echo "<br>";
}

?>
 Example : Continue Statement
<?php
error_reporting(0);
for($i<=1;$i<=10;$i++)
{
if($i%2==0)
{
continue;
}
else
{
echo $i;
}
echo "<br>";
}

?>
 Example : While Loop
<?php
$n=1;
while($n<=10)
{
echo $n;
echo "<br>";
$n++;
}

?>
 Example : Do-While Loop
<?php
$n=1;
do
{
echo $n;
echo "<br>";
$n++;
}while($n<=10);

?>
 Example : For Loop
<?php
//error_reporting(0);
for($i<=1;$i<=10;$i++)
{
echo $i;
echo "<br>";
}

?>
 Example : Simple Array
<?php

error_reporting(0);

$subj = array("PHP","C++","DS","Java");

echo "Value of Index 0=".$subj[0];

echo "<br>";

print_r($subj);

echo "<br>";

$stud_nm = array();

$stud_nm[] = "Rasmus";

$stud_nm[] = "Andy";

$stud_nm[] = "Tom";

$stud_nm[] = "James";

echo "Value of Index 3=".$stud_nm[3];

echo "<br>";

print_r($stud_nm);

?>
 Example : Associative Array
<?php
$emp = array(
"name" => "Andy",
"desig" => "Programmer",
"age" => 25
);
echo $emp["name"];
echo "<br>";
foreach($emp as $key=>$val)
{
echo $key." = ".$val;
echo "<br>";
}

?>
 Function
 A function is a self-contained block of code that can be called by your
scripts.
 When called, the functions code is executed.
 You can pass values to functions, which they then work with. When
finished, a function can pass a value back to the calling code.
 Syntax :
function function_nm($arg1, $arg2,…., $argn)
{
// Function Code
}
 Example :
<?php

function demo()

{
echo "<h1>Hello from function</h1>";

demo();

?>

 User Defined Function (UDF)


1) ARGUMENT FUNCTION
 Information may be passed to functions via the argument list, which is a
comma-delimited list of expressions.
 PHP support passing arguments by value, passing by reference, and default
argument values.
 Variable length argument lists are supported only in PHP 4 and later.
 Example :

function sum($a,$b)

$ans = $a + $b;

echo "Ans is : ".$ans;

sum(10,20);

2)DEFAULT ARGUMENT
 A function may define C++ style default values for scalar arguments.
 You can write yout function to have default values.
 For Example you can define an argument as having a default value, which
the parameters for that argumenys will adopt when the function call,
provided you don’t pass a value in for that argument.
 Example :
function makecoffee($type="cappuccino")

echo "Making a cup of $type<br>";

echo makecoffee();

echo makecoffee("milk");

3) VARIABLE FUNCTION
 PHP support the concept of variable function.
 This means that if a variable name has parantheses appended to it, PHP will
look for a function with the same name as whatever the variable evaluates
to, and will attempt to execute it.
 Variable function wont work with language construct such as echo(),
print(), unset(), isset(), empty().
 Example :

function test()

echo "Test function called using variable functions";

$fun_holder = "test";

$fun_holder();

4) RETURN FUNCTION
 Values are returned by using the optional return statement.
 Any type may be returned, including lists and objects.
 This causes the function to end its execution immediately and pass control
back to the line from which it was called.
 Example :

function square($a)

$s = $a* $a;

echo "Square of $a is $s";

square(8);

?>

 Example : Variable Scope : Local , Global , Static


 Static Scope
 Normally, when a function is completed/executed, all of its
variables are deleted. However, sometimes we want a local
variable NOT to be deleted. We need it for a further job.
 To do this, use the static keyword when you first declare the
variable.
 Example :
<?php

function myTest()
{
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();

 Local Scope
 A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function.
 Example :
function myTest()
{
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";

 Global Scope
 A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function.
 The global keyword is used to access a global variable from within a
function.
 To do this, use the global keyword before the variables (inside the
function).
 Example :
$x = 5; // global scope
function myTest()
{
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";

$x = 5;
$y = 10;

function myTest()
{
global $x, $y;
$y = $x + $y;
}

myTest();
echo $y; // outputs 15

?>
 Example : Variable Length Argument Function
1) func_num_args()
 Return the number of arguments passed into the current user defined
function.
 This function will generate a warning if called from outside of a user
defined function.
 Syntax :
int func_num_args()
 Example :

<?php

function test()

$numargs = func_num_args();

echo "Number of arguments is : $numargs";


}

test(2,3);

2)func_get_arg()
 Return an item from the argument list.
 Function arguments are counted starting from zero.
 Syntax :
mixed func_get_arg(int arg_num)
 Example :
<?php

function test()

$numargs = func_num_args();

echo "Number of arguments is : $numargs";

if($numargs >=2)

echo "The second argument is:".func_get_arg(1);

test(10,20,30);

3) func_get_args()
 Return an array comprising a function argument list.
 It will generate a warning if called from outside a function definition.
 Syntax :
array func_get_args()
 Example :
<?php

function test()

$numargs = func_num_args();

echo "Number of arguments is : $numargs";

if($numargs >=2)

echo "The second argument is:".func_get_arg(1);

$arg_list = func_get_args();

for($i=0;$i<$numargs;$i++)

echo "Argument $i is: ".$arg_list[$i]."<br>";

test(1,2,3);

?>

 Example : Variable Function


 gettype()
 This function will return the type of a variable.
 Syntax :
String gettype(mixed var)
 settype()
 Set the type of variable.
 Syntax :
Bool settype(mixed var, string type)
 isset()
 Determine whether a variable is set or not.
 Syntax :
bool isset(mixed var)
 unset()
 unset a given variable.
 Syntax :
Void unset(mixed var)
 strval()
 Get string value of a variable.
 Syntax :
String strval(mixed var)
 intval()
 Get integer value of a variable.
 Syntax :
int intval(mixed var)
 floatval()
 Get float value of a variable.
 Syntax :
float floatval(mixed var)
 Example :
<?php
error_reporting(0);
//gettype()
$test;
print gettype($test);
$test=15;
print "<br>".gettype($test);
$test="Hello";
print "<br>".gettype($test);
$test=true;
print "<br>".gettype($test);

//settype()
$var = 3.14;
echo gettype($var);

settype($var,string);
echo "<br>".gettype($var);

settype($var,int);
echo "<br>".gettype($var);
echo "<br>".$var;

settype($var,bool);
echo "<br>".gettype($var);
echo "<br>".$var;

//isset() and unset()


$a = "";
if(isset($a))
{
echo "variable a is defined";
}
else
{
echo "variable a is not defined";
}
echo "<br>";
if(isset($b))
{
echo "variable b is defined";
}
else
{
echo "variable b is not defined";
}
unset($a);
echo "<br>";
if(isset($a))
{
echo "variable a is defined";
}
else
{
echo "variable a is not defined";
}

//strval()
$var = 3.14;
$mystr1 = strval($var);
echo $mystr1;

//intval()
$mystr2 = intval($var);
echo "<br>".$mystr2;

//floatval()
$mystr3 = floatval($var);
echo "<br>".$mystr3;
?>
 Array Library Function
1) Count()
Count how many element in an array.
Syntax : Int count(mixed var)
Example : $a[0]=10;
$a[1]=10;
echo $res = count($a);
$a[2]=10;
$a[3]=10;
echo "<br>".$res = count($a);

2) list()
Assign variable as if they were an array.
List is used to assign a list of variables in one operation.
Syntax : Void list(mixed varname, mixed…)
Example :
$info = array('coffee','brown','caffeine');
list($drink,$color,$power)=$info;
echo "$drink is $color and $power makes it special";

3) in_array()
Check if value exist in an array or not
Syntax : Bool in_array(mixed needle, array haystack)
Example :
$arr = array("php","unix","java","ds");
if(in_array("php",$arr))
{
echo "php is in an array";
}
else
{
echo "it is not in an array";
}

4) current()
Return the current element in an array.
Syntax : Mixed current(array arr)

5) next()
Advance the internal array pointer of an array.
Syntax : Mixed next(array arr)

6) prev()
Rewind the internal array pointer.
Syntax : Mixed prev(array arr)

7) end()
set the internal pointer of an array to its last element
Syntax : mixed end(array arr)
Example :
$transport = array("bike","car","plane","honda");
echo "Current Element is = ".current($transport);
echo "<br>Next Element is = ".next($transport);
echo "<br>Prev. Element is = ".prev($transport);
echo "<br>Last Element is = ".end($transport);

8) each()
Return the current key and value pair from an array.
Syntax : Array each(array arr)
Example :
$foo = array("andy","rubin","james","rasmus");
$bar = each($foo);
print_r($bar);
9) sort()
This function sort an array. Element will be arranged from lowest to highest
when this function has been completed.
Syntax : Bool sort(array arr)
Example :
$fruit = array("lemon","orange","banana","apple");
sort($fruit);
foreach($fruit as $key => $val)
{
echo "fruit[$key] = $val<br>";
}

10) rsort()
sort an array in reverse order.
Syntax : Bool rsort(array arr)
Example :
$fruit = array("lemon","orange","banana","apple");
rsort($fruit);
foreach($fruit as $key => $val)
{
echo "fruit[$key] = $val<br>";
}

11) asort()
Sort an array and maintain index association.
Syntax : Bool asort(array arr)
Example :
$fruits = array(
"d"=>"lemon",
"a"=>"orange",
"b"=>"banana",
"c"=>"apple"
);
asort($fruits);
foreach($fruits as $key=>$val)
{
echo "$key=$val";
echo "<br>";
}

12) array_merge()
Merge one or more array.
Syntax : array array_merge(array arr1 [,array arr2….])
Example :
$arr1 = array("C","C++","DS","Java");
$arr2 = array("Ruby","Perl","Android","iPhone");
$res = array_merge($arr1,$arr2);
print_r($res);

13) array_reverse()
Reverse an array with element in reverse order.
Syntax : Array array_reverse(array arr)
Example :
$arr1 = array("C","C++","DS","Java");
print_r(array_reverse($arr1));

14) array_diff()
It return an array containing all value of arr1 that are not present in any of the
other arguments.
Syntax : array array_diff(array arr1,array arr2)
Example :
$arr1 = array("a"=>"green","red","blue","red");
$arr2 = array("b"=>"green","yellow","red");
$res = array_diff($arr1,$arr2);
print_r($res);
15) array_shift()
Shift an element off the beginning of array. Shift the first value of the array off
and return it.
Syntax : Mixed array_shift(array arr)
Example :
$stack = array("lemon","orange","banana","apple");
$fruit = array_shift($stack);
print_r($fruit);

16) array_slice()
It return the sequence of element from the array as specified by offset and
length elements.
Syntax : Array array_slice(array arr, int offset[,int len])
Example :
$input = array("a","b","c","d","e");
print_r(array_slice($input,2));
echo "<br>";
print_r(array_slice($input,2,-1));
echo "<br>";
print_r(array_slice($input,-2,1));

17) array_unique()
Remove duplicate value from an array.
Syntax : Array array_unique(array arr)
Example :
$input = array("a"=>"green","red","b"=>"green","blue","red");
$res = array_unique($input);
print_r($res);

18) array_unshift()
Prepend one or more element to the beginning of the array.
Syntax : Int array_unshift(array arr,mixed var)
Example :
$queue = array("orange","rasberry");
array_unshift($queue,"apple","banana");
print_r($queue);

19) array_keys()
Return all the keys of an array.
Syntax : Array array_keys(array arr)
Example :
$arr = array(0=>100,"color"=>"red");
print_r(array_keys($arr));

20) array_key_exists()
Check if the given key or index exist in the array or not.
Syntax : Bool array_key_exists(mixed key, array search)
Example :
$arr = array("first"=>"php","second"=>"ds");
if(array_key_exists("first",$arr))
{
echo "First element is in an array";
}

21) array_push()
push one or more element onto the end of an array.
Syntax :Int array_push(array arr,mixed var)
Example :
$x = array("orange","banana");
array_push($x,"apple","rasberry");
print_r($x);

22) array_pop()
Pop the elements off the end of array.
Syntax : Mixed array_pop(array arr)
Example :
$stack = array("orange","banana","apple","rasberry");
$fruit = array_pop($stack);
print_r($stack);

 Example : String Library Function


1) chr()
Return a one character string containing the character specified by ascii.
Syntax : string chr(int ascii)
Example :
echo chr(65);
echo "<br>".chr(97);

2) ord()
Return the ASCII value of the first character of string.
Syntax : int ord(string str)
Example :
echo ord("A");
echo "<br>".ord("Hello");

3) strtolower()
Return string with all alphabetic characters converted to lowercase.
Syntax : string strtolower(string str)
Example :
echo strtolower("B.V. DHANAK COLLEGE");

4) strtoupper()
Return string with all alphabetic characters converted to uppercase.
Syntax : string strtolower(string str)
Example :
echo strtoupper("b.v. dhanak college");
5) strlen()
Return the length of the given string.
Syntax : int strlen(string str)
Example :
echo strlen("wel come");

6) ltrim()
Remove white space from the beginning of a string.
Syntax : String ltrim(string s)
Example :
$str = " Welcome";
echo "Before trimming Length is = ".strlen($str);
$str = ltrim($str);
echo "<br> After trimming Length is = ".strlen($str);

7) rtrim()
Remove white space from the end of a string.
Syntax : String rtrim(string s)
Example :
$str = "Welcome ";
echo "Before trimming Length is = ".strlen($str);
$str = rtrim($str);
echo "<br> After trimming Length is = ".strlen($str);

8) trim()
Remove white space from the beginning and ending of a string.
Syntax : String trim(string s)
Example :
$str = " Welcome ";
echo "Before trimming Length is = ".strlen($str);
$str = trim($str);
echo "<br> After trimming Length is = ".strlen($str);
9) substr()
Return part of a string.
Syntax : String substr(string s, int start [, int length])
Example :

echo substr("abcdef",-1);
echo "<br>".substr("abcdef",-2);
echo "<br>".substr("abcdef",-3,1);

10) strcmp()
Binary safe string comparison.
Syntax : int strcmp(string str1, string str2)
Return < 0 if str1 is less than str2, > 0 if str1 is greater than str2, and 0 if they
are equal.
Example :
echo strcmp("Hello","hello");

11) strcasecmp()
Binary safe case- insensitive string comparison.
Syntax : int strcasecmp(string str1, string str2)
Example :

$var1 = "dhanak";
$var2 = "DHANAK";
if(strcasecmp($var1,$var2)==0)
{
echo "$var1 is equal to $var2 in a case insensitive string comparison";
}

12) strpos()
Find position of first occurance of a string.
Syntax : int strpos(string haystack, mixed needle)
Example :
$str = "abc";
$find = 'a';
$pos = strpos($str,$find);
if($str == false)
{
echo "The string $find was not found in the string $str";
}
else
{
echo "The string $find was found in the string $str and exists at
position $pos";
}
13) strrpos()
Find position of last occurance of a string.
Syntax : int strrpos(string haystack, mixed needle)
Example :
$newstr = "abcdef abcdef";
echo $pos = strrpos($newstr,'a');
14) strstr()
Find first occurance of a string.
Syntax : string strstr(string haystack, string needle)
Example :
$email = "[email protected]";
echo $domain = strstr($email,'@');
15) stristr()
case insensitive of strstr().
Syntax : string stristr(string haystack, string needle)
Example :
$email = "[email protected]";
echo $domain = stristr($email,'L');

16) str_replace()
Replace all occurance of the search string with the replacement string.
Syntax : string str_replace (mixed search, mixed replace, mixed subject)
Example :
$vowels = array("a","e","i","o","u","A","E","I","O","U");
echo $x = str_replace($vowels,"*","Hello world of PHP");
17) strrev()
Return reverse a string.
Syntax : String strrev(String str)
Example :
echo strrev("Hello");
18) print()
output a string
Syntax : int print(String arg)
Example :
print("Hello world");
print "<br>print() also work without breakets";
print "<br>This spans
multiple lines. The newline will be
output as well";
19) explode()
This function convert string into an array.
Syntax : array(String separator, String str)
Example :
$str = "andy rasmus ledorf rubin";
$arr = explode(" ",$str);
print_r($arr);

20) implode()
This function convert array into string.
Syntax : string implode(String glue, array pieces)
Example :
$arr = array("fname","lname","email");
$comma_seprated = implode(",",$arr);
echo $comma_seprated;
21) md5()
Calculate the md5 hash of a string.
Syntax : string md5(String s)
Example :
$str = "apple";
if(md5($str) == "1f3870be274f6c49b3e31a0c6728957f")
{
echo "would you like a green or red apple";
}
22) str_split()
Convert a string into an array.
Syntax : array str_split(String s [,int split_length])
Example :
$str = "Hello world";
$arr1 = str_split($str);
print_r($arr1);
echo "<br>";
$arr1 = str_split($str,3);
print_r($arr1);

23) substr_count()
Count the number of substring occurances.
Syntax : int substr_count(String haystack, string needle)
Example :
echo substr_count("This is a test","is");

24) ucfirst()
Makes string first character uppercase.
Syntax : String ucfirst(String str)
Example :
echo ucfirst("welcome To LAMP");
25) ucwords()
Uppercase the first character of each words in a string.
Syntax : string ucwords(String s)
Example :
echo ucwords("welcome to lAMP");

 Example : Maths Library Function

1) abs()

Return absolute value.

Syntax : number abs(mixed number)

Example : echo abs(-4);

echo "<br>".abs(5);

2) ceil()

Round Fractions up.

Syntax : float ceil(float value)

Example : echo ceil(4.3);

echo "<br>".ceil(9.99);

3) floor()

Round fractions down.

Syntax : float floor(float value)

Example : echo floor(4.3);

echo "<br>".floor(9.99);
4) round()

Returns the rounded value of val.

Syntax : float round(float val)

Example : echo round(3.4);

echo "<br>".round(3.5);

echo "<br>".round(3.6);

5) fmod()

Return the floating point reminder of dividing the dividend(x) by the


divisor(y).

Syntax : float fmod(float x, float y)

Example : echo fmod(10,3);

6) min()

Find minimum value from a list.

Syntax : mixed min(number arg1, number arg2,….)

Example : echo min(2,5,4,6,8,9);

7) max()

Find maximum value from a list.

Syntax : mixed max(number arg1, number arg2,….)

Example : echo max(2,5,4,6,8,9);

8) pow()
Return base raised to the power of exp.

Syntax : Number pow(number base, number exp)

Example : echo pow(2,2);

9) sqrt()

Return square root.

Syntax : Float sqrt(float arg)

Example : echo sqrt(25);

10) exp()

Calculate the exponent of e

Syntax : Float exp(float arg)

Example : echo exp(5.7);

11) rand()

Generate a random integer number.

Syntax : Int rand([int min, int max])

Example : echo rand();

echo "<br>".rand(5,15);

12) cos()

Return the cosine value.

Syntax : Float cos(float arg)

Example : echo cos(0.70);


13) acos()

Return the arc cosine value.

Syntax : Float acos(float arg)

Example : echo "<br>".acos(0.65);

14) sin()

Return the sine value.

Syntax : Float sin(float arg)

Example : echo sin(60);

15) asin()

Return the arc sine value.

Syntax : Float asin(float arg)

Example : echo asin(0.35);

16) tan()

Return the tangent value.

Syntax : Float tan(float arg)

Example : echo "<br>".tan(1.23);

17) atan()

Return the arc tangent value.

Syntax : Float atan(float arg)

Example : echo "<br>".atan(1.23);


18) bindec()

Return binary to decimal

Syntax : Int bindec( String binary_string)

Example : echo bindec("110011");

echo "<br>".bindec("1111");

19) decbin()

Return decimal to binary.

Syntax : String decbin(int number)

Example : echo decbin("12");

echo "<br>".decbin("15");

20) hexdec()

Return hexadecimal to decimal

Syntax : Int hexdec(String hex_string)

Example : var_dump(hexdec("f"));

 File Handling (File System) Function

1) fopen()

Open a file.

Syntax : resource fopen(String filenm, string mode)


Mode Description
R Opening for reading only
r+ Opening for reading and writing
W Open for writing only
w+ Open for reading and writing only
A Open for writing only
a+ Open for reading and writing

2) fread()

It is used to read data from a file.

Syntax : String fread(resource handle, int length)

3) fclose()

Closes an open file pointer.

Syntax : Bool fclose(resource handle)

Example :

$filename = "abc.txt";

$handle = fopen($filename,"r");

$content = fread($handle,filesize($filename));

echo $content;

fclose($handle);

4) fwrite()

It is used to write the content of string to the file stream pointed to


by handle.

Syntax : Int fwrite(resource handle, String s)

Example :

$filename = "abc.txt";
$newline = "add this to the file";

$handle = fopen($filename,"a");

fwrite($handle,$newline);

fclose($handle);

5) file_exists()

Checks whether a file or directory exists or not.

Syntax : Bool file_exists(String filenm)

Example :

$filename = "abc.txt";

if(file_exists($filename))

echo "The file $filename exists";

else

echo "The file $filename does not exists";

6) is_readable()

Tells whether the filename is readable or not.

Syntax : Bool is_readable(String filenm)


Example :

$filename = "abc.txt";

if(is_readable($filename))

echo "The file is readable";

else

echo "The file is not readable";

7) is_writable()

Tells whether the filename is writable or not.

Syntax : Bool is_writable(String filenm)

Example :

$filename = "abc.txt";

if(is_writable($filename))

echo "The file is writable";

else
{

echo "The file is not writable";

8) fgets()

Get line from file pointer.

Syntax : String fgets(resource handle[,int len])

Example :

$handle = fopen("xyz.txt","r");

while(!feof($handle))

$buffer = fgets($handle,4096);

echo $buffer;

fclose($handle);

9) fgetc()

Get a character from the given file pointer.

Syntax : String fgetc(resource handle)

Example :

$fp = fopen("abc.txt","r");

if(!$fp)
{

echo "could not open file";

while(false !== ($char = fgetc($fp)))

echo "$char<br>";

fclose($fp);

10) file()

Reads entire file into an array.

Syntax : Array file(String filenm)

Example :

$lines = file("xyz.txt");

foreach($lines as $line_num => $line)

echo "Line= <b>{$line_num}<b> :".$line."<br>";

11) file_get_contents()

Reads a entire file into a string.

Syntax : String file_get_contents(String filenm)


Example :

echo $str = file_get_contents("xyz.txt");

12) file_put_contents()

write a string to a file.

Syntax : Int file_put_contents(String filenm, mixed data)

Example :

$file = "people.txt";

$current = "This is the demo of file_get_contents";

file_put_contents($file,$current);

13) ftell()

Tell file pointer read/write position.

Syntax : Int ftell(resource handle)

Example :

$fp = fopen("people.txt","r");

$data = fgets($fp,12);

echo ftell($fp);

fclose($fp);

14) fseek()

Seeks on a file pointer.

Syntax : Int fseek(resource handle, int offset)


Example :

$fp = fopen("abc.txt","r");

$data = fgets($fp,4096);

echo ftell($fp);

fseek($fp,0);

echo "<br>".ftell($fp);

15) rewind()

Sets the file position indicator for handle to the beginning of the file
stream.

Syntax : bool rewind(resource handle)

Example :

$h = fopen("output.txt","w+");

fwrite($h,"This is first sentence");

rewind($h);

fwrite($h,"foo");

rewind($h);

echo fread($h,filesize("output.txt"));

fclose($h);

16) copy()

copies file.
Syntax : Bool copy(String source, string dest)

Example :

$file = "xyz.txt";

$newfile = "new.txt";

copy($file,$newfile);

echo "Copy the file";

17) unlink()

Deletes a file.

Syntax : Bool unlink(String filenm)

Example :

$file = "people.txt";

unlink($file);

echo "file deleted";

18) rename()

Rename a file or directory.

Syntax : Bool rename(String oldnm, String newnm)

Example :

rename("xyz.txt","aaa.txt");

echo "renaming the file";

 Date and Time Function


1) date()
Format a local time/date.
Syntax : String date(String format)

Format Description Example


Character
d Day of Month with leading zero 01 to 31
D Textual representation of a day Mon through Sun
J Day of month without leading zero 1 to 31
L A full textual representation of the day Sunday Through Saturday
W Numeric representation of the day of 0(for sun) through 6 (For
the week sat)
z The day of the year 0 to 365
F Full textual representation of month January to December
m Numeric representation of month with 01 to 12
leading zeros
M A short textual representation of a Jan through Dec
month, three letters
n Numeric representation of a month, 1 to 12
without leading zeros
t Number of days in the given month 28 through 31
L Whether it’s a leap year 1 or 0
Y Fully numeric representation of a 1999
year, 4 digit
y Two digit representation of year 99
a Lowercase Ante Meridiem and post am or pm
meridiem
A Uppercase Ante Meridiem and post AM or PM
meridiem

Example :
echo date(d."-".D."-".l);
echo "<br>".date(N."-".z."-".F);
echo "<br>".date(W."-".m."-".M);
echo "<br>".date(n."-".t."-".L);
echo "<br>".date(Y."-".y);
2) checkdate()
Validate a given date.
Syntax : Bool checkdate(int month, int day, int year)
Example :
var_dump(checkdate(12,31,2000));
echo "<br>";
var_dump(checkdate(2,29,2001));

3) time()
Return current Unix timestamp.
Syntax : Int time()
Example :
$nextweek = time() + (7*24*60*60);
echo "Now : ".date('Y-m-d');
echo "<br>Next Week : ".date('Y-m-d',$nextweek);

4) date_create()
Return new DateTime object.
Syntax : Datetime date_create(String time)

5) date_add()
Adds an amount of days, months, years, hours, miniutes, and seconds to a
Datetime object.
Syntax : Datetime date_add(DateTime object, DateInterval interval)

6) date_format()
Return date formatted according to given format.
Syntax : String date_format(DateTime obj, String format)
Example :
$date = date_create('2017-01-01');
date_add($date,date_interval_create_from_date_string('10 days'));
echo date_format($date,'Y-m-d');
 Miscellaneous Function
1) define()
This function will define the named constant.
Syntax : bool defined(String name, mixed value)

2) defined()
This function will check whether named constant exists.
Syntax : bool defined(String name)

3) constant()
This will return the value of a constant.
Syntax : mixed constant(String name)
Example :
<?php
error_reporting(0);
define("PI",3.14);
define("COLLEGE","B.V.Dhanak");
echo PI;
echo COLLEGE;
if(defined("PI"))
{
echo "Constant PI is defined";
}
echo constant(“PI”);
?>

4) exit()
Output a message and terminate the current script.
void exit()

5) die()
Output a message and terminate the current script.
 GET and POST method
 When defining the method a web browser should use to send variable to the page
specified by your action, you either use GET or POST.
 GET sends its variable in the URL of your visitors web browsers, which makes it
easy to see what was sent.
 However, it also makes it very easy for visitors to change what was sent, and
moreover, there is usually a fairly low limit on the number of characters that can
be sent in a URL – normally fewer than 250
 As a result, if you send long variable using GET, you are likely to lose large
amount of it.
 POST on the other hand sends its variables hidden to your user, which means that
it is much harder to understand.
 It cannot be changed without some effort on your visitors behalf, and has a much
higher limit(usually megabytes) on the amount of data that can be sent.

You might also like