Unit-1
Unit-1
<?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;
?>
if($a == $b)
{
echo "<br>Both are equal";
}
else
{
echo "<br>Both are not equal";
}
if($a != $b)
{
echo "<br>a is not equal to b";
}
?>
Example : Conditional Operator
<?php
$a=20;
$b=10;
echo "<br>";
$s = "Rasmus ";
$nm = $s."Ledorf";
echo $nm;
?>
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 : 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 "<br>";
print_r($subj);
echo "<br>";
$stud_nm = array();
$stud_nm[] = "Rasmus";
$stud_nm[] = "Andy";
$stud_nm[] = "Tom";
$stud_nm[] = "James";
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();
?>
function sum($a,$b)
$ans = $a + $b;
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 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()
$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;
square(8);
?>
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();
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();
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();
if($numargs >=2)
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();
if($numargs >=2)
$arg_list = func_get_args();
for($i=0;$i<$numargs;$i++)
test(1,2,3);
?>
//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;
//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);
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");
1) abs()
echo "<br>".abs(5);
2) ceil()
echo "<br>".ceil(9.99);
3) floor()
echo "<br>".floor(9.99);
4) round()
echo "<br>".round(3.5);
echo "<br>".round(3.6);
5) fmod()
6) min()
7) max()
8) pow()
Return base raised to the power of exp.
9) sqrt()
10) exp()
11) rand()
echo "<br>".rand(5,15);
12) cos()
14) sin()
15) asin()
16) tan()
17) atan()
echo "<br>".bindec("1111");
19) decbin()
echo "<br>".decbin("15");
20) hexdec()
Example : var_dump(hexdec("f"));
1) fopen()
Open a file.
2) fread()
3) fclose()
Example :
$filename = "abc.txt";
$handle = fopen($filename,"r");
$content = fread($handle,filesize($filename));
echo $content;
fclose($handle);
4) fwrite()
Example :
$filename = "abc.txt";
$newline = "add this to the file";
$handle = fopen($filename,"a");
fwrite($handle,$newline);
fclose($handle);
5) file_exists()
Example :
$filename = "abc.txt";
if(file_exists($filename))
else
6) is_readable()
$filename = "abc.txt";
if(is_readable($filename))
else
7) is_writable()
Example :
$filename = "abc.txt";
if(is_writable($filename))
else
{
8) fgets()
Example :
$handle = fopen("xyz.txt","r");
while(!feof($handle))
$buffer = fgets($handle,4096);
echo $buffer;
fclose($handle);
9) fgetc()
Example :
$fp = fopen("abc.txt","r");
if(!$fp)
{
echo "$char<br>";
fclose($fp);
10) file()
Example :
$lines = file("xyz.txt");
11) file_get_contents()
12) file_put_contents()
Example :
$file = "people.txt";
file_put_contents($file,$current);
13) ftell()
Example :
$fp = fopen("people.txt","r");
$data = fgets($fp,12);
echo ftell($fp);
fclose($fp);
14) fseek()
$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.
Example :
$h = fopen("output.txt","w+");
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);
17) unlink()
Deletes a file.
Example :
$file = "people.txt";
unlink($file);
18) rename()
Example :
rename("xyz.txt","aaa.txt");
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.