Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

BCA Notes PHP

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

INTRODUCTION

• PHP

• Rasmus Lerdorf in 1994

• Personal Home Page Tools(’94 and ‘95) – for logging


INTRODUCTION
Why PHP ???
• Portability
• Open Source
• Loosely typed language
• Easy to use
INTRODUCTION
• WAMP LAMP MAMP
• WORKING

www.abc.com/xyz.html
HTML code
Client
APACHE
(Web Browser) www.abc.com/trial.php PHP Engine

trial.php

xyz.html

MySQL

WINDOWS
WAMP STRUCTURE
• Configuration Files

• phpMyAdmin
LEXICAL STRUCTURE
• SYNTAX
<?php
• //code;
•?>
• VARIABLES - What is a variable?
RULES
1) A variable name starts with a $ sign, followed by the name of the
variable.
2) A variable name must begin with a letter or the underscore
character.
3) A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _).
4) A variable name should not contain spaces.
5) Variable names are case sensitive.
EXAMPLES
• $var
• $this_is_a variable
• $2name
• $name2
• $_name2
• $name|
• Is $username the same as $Username?
CONSTANTS
• SYNTAX :
define(name, value, case_insensitive);
• E.g. define(“PI”,3.14);
COMMENTS
• Shell-style(#)
• C++ style(//)
• C style(/**/)
DATATYPES
• Type Juggling
• SCALAR TYPES
•Integers - is_int, is_integer, notations
•Floating-point numbers - is_real, is_float, notations
•Strings
• - is_string
• - quotes
• - escape sequence characters(\,”,’,$),
•Booleans - is_bool, false values
• COMPOUND TYPES
•Arrays - indexed and associative, is_array
•Objects
• SPECIAL TYPES
•Resource - is_resource, created and used by special functions
•Null - is_null
DATATYPES
• gettype()
• settype(var_to_change, new_datatype)
• Casting
• int, integer
• bool, boolean
• float, double, real
• string
• array
• object
OPERATORS
• ARITHMETIC OPERATORS : +,-,*,/,%,negation(-)
• ASSIGNMENT OPERATORS : =,+=,-=,*=, /=, %=,
• STRING OPERATORS : ., .=
• INCREMENT/DECREMENT OPERATORS : ++, --
• COMPARISON OPERATORS : ==, ===, !=, <>, !==, >, <, >=, <=
- TERNARY OPERATOR : (condition)?true_statement:false_statement
• LOGICAL OPERATORS : and, or, xor, &&, ||, !
• BITWISE OPERATORS : &, |, ^, ~, <<, >>
• ERROR CONTROL OPERATOR : @
• ARRAY OPERATORS : +, ==, ===, !=, <>, !==
OPERATOR PRECEDENCE
++ -- (cast)
/*%
+-
< <= >= >
== === != <>
&&
||
= += -= /= *= %= .=
and
xor
or
CONTROL STRUCTURES
• if-else
• switch
• while
• do-while
• for
• foreach
• break
• continue
• include
• require
• goto
FUNCTIONS
• SYNTAX for creating a User-Defined Function
• function <function_name>(<parameters_if_any>)
{
//code
}
• Case-insensitive
• A function can be declared only once in PHP
• return statement
- How to return multiple values???
FUNCTIONS
• Arguments
 By value and by reference(&)
 Default argument values
 Variable length argument lists
- func_num_args
- func_get_args
- func_get_arg(argument_number)
 Missing parameters
FUNCTIONS
• Variable functions
function display()
{
Echo “Inside function”;
}
$name=“display”;
$name();

• Anonymous functions
$anonymous_function = create_function('$a, $b', 'return $a*$b;');
print $anonymous_function(3,7);

• Recursive functions
E.g. Fibonacci Series
FUNCTIONS
• Variable Scope
• Global Variables – global and $GLOBALS[‘variable_name’]

• Static Variables
• Alternative Syntax for ‘for’:
for($i=0;$i < 10;$++i) :
// code goes here
endfor;

• Alternative Syntax for ‘if’:


if(<condition>) :
//code goes here
else :
//code goes here
endif;

• Assigning variable by reference


$a=&$b;
By default, variables are assigned by value

• Variable variables - A variable variable takes the value of a variable and


treats that as the name of a variable.
$a="hello";
$$a="world";
echo ${$a};
echo $$a;
1.$number=50;

function tenTimes()
{
$number = $number * 10;
}
tenTimes();
print $number;

2.for($i=1; $i<=5; $i++)


{
for($j=10; $j>=$i; $j--)
{
echo $j;
}
echo "<br>";
}
ARRAYS
• Indexed/Numeric/Enumerated Arrays
- Creation
- Accessing elements

• Associative Arrays
- Creation
- Accessing elements
- Unique keys
- Quotes

• Appending
- key can be <0

• Multidimensional Arrays – creation and accessing elements


ARRAY FUNCTIONS
1. range()
The range( ) function creates an array of consecutive integer or
character values between the two values you pass to it as arguments.

$numbers = range(2, 5);


range(‘a’, ‘z’);
range(5, 2);

Only the first letter of a string argument is used to build the range:
range(‘aaa’, ‘zzz’)
ARRAY FUNCTIONS
2. count() and sizeof()

$arr = array(“colleges”,”schools”,1,33,44);
echo count($arr);

3. array_pad(array,size,value)
inserts the specified no. of elements, with the specified value, to an array

$a=array("Dog”,"Cat");
$x=array_pad($a,5,0);

$a=array("Dog","Cat");
$x=array_pad($a,-5,0);
ARRAY FUNCTIONS
4. array_slice()

$people = array(‘Mark’,’Jane’,’Smith’,’Linda’,’Amy’);
$middle = array_slice($people, 2, 2);

5. array_chunk(array, size[, preserve_keys])

$nums = range(1, 7);


$rows = array_chunk($nums, 3);
print_r($rows);
$rows = array_chunk($nums, 3,true);
print_r($rows);
ARRAY FUNCTIONS
6. array_keys() and array_values()

7. array_key_exists(key,array)

8. array_splice(array,start[,length,array2])
$subjects = array('physics', 'chem', 'math', 'bio', 'cs', 'drama', 'classics');
$removed = array_splice($subjects, 2, 3);
var_dump($subjects);
var_dump($removed);

$removed = array_splice($subjects,2);

$new = array('law', 'business', 'IS');


array_splice($subjects, 4, 3, $new);
ARRAY FUNCTIONS
Also works with associative arrays :

$capitals = array(
'USA' => 'Washington',
'Great Britain' => 'London',
'New Zealand' => 'Wellington',
'Australia' => 'Canberra',
'Italy' => 'Rome');

$down_under = array_splice($capitals, 2, 2);

$france = array('France' => 'Paris');


array_splice($capitals, 1, 0, $france);
ARRAY FUNCTIONS
9. extract()

$person = array('name' => ‘Mark’, 'age' => ’35’, ‘place' => ‘India’);

extract($person);

10. compact()

$color = 'indigo'; $shape = 'curvy'; $floppy = 'none';


$a = compact('color', 'shape', 'floppy');
ARRAY FUNCTIONS
11. array_walk(array, function[, parameter...])
function myfunction($value,$key)
{
echo "The key $key has the value $value<br />";
}
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");
array_walk($a,"myfunction");

function myfunction($value,$key,$p)
{
echo "$key $p $value<br />";
}
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");
array_walk($a,"myfunction","has the value");

function myfunction(&$value,$key)
{
$value="Bird";
}
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");
array_walk($a,"myfunction");
print_r($a);
ARRAY FUNCTIONS
12. array_reduce(array, function[, initial])
E.g. <?php
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction"));
?>

function myfunction($v1,$v2)
{
static $ctr=-1;
$ctr++;
//echo $ctr;
echo $v1;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction","asdasdas"));
ARRAY FUNCTIONS
13. in_array(search, array)

14. array_reverse(array[, preserve])


15. shuffle(array)
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

shuffle($my_array);
print_r($my_array);
16. array_sum(array)
17. array_merge(array1[,array2,array3...])
<?php
$a1=array("a"=>"Horse","b"=>"Dog");
$a2=array("c"=>"Cow","b"=>"Cat");
print_r(array_merge($a1,$a2));
?>
<?php
$a=array(3=>"Horse",4=>"Dog");
print_r(array_merge($a));
?>
ARRAY FUNCTIONS
18. array_unique(array)
<?php
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
print_r(array_unique($a));
?>

19. array_push(array, value1[, value2,…])


<?php
$a=array("Dog","Cat");
array_push($a,"Horse","Bird");
print_r($a);
?>
20. array_pop()
<?php
$a=array("Dog","Cat","Horse");
array_pop($a);
print_r($a);
?>
ARRAY FUNCTIONS
21. array_diff(array1, array2[, array3,…])
<?php
$a1=array(0=>"Cat",1=>"Dog",2=>"Horse");
$a2=array(3=>"Horse",4=>"Dog",5=>"Fish");
print_r(array_diff($a1,$a2));
?>
ARRAY FUNCTIONS
22. array_filter(array, function)
The array_filter() function passes each value in the array to a user-
made function, which returns either true or false, and returns an array
only with the values that returned true.
<?php
function myfunction($v)
{
if ($v==="Horse")
{
return true;
}
return false;
}
$a=array(0=>"Dog",1=>"Cat",2=>"Horse");
print_r(array_filter($a,"myfunction"));
?>
ARRAY FUNCTIONS
23. list()

ONLY WORKS ON NUMERIC / ENUMERATED/ INDEXED ARRAYS

$values = range('a', 'e');


list($m,,$n,,$o) = $values;
SORTING ARRAYS
1a. sort(array[, sort_type])
SORT_REGULAR
SORT_NUMERIC
SORT_STRING
E.g.
$my_array = array(“first”=>"100a",”second”=>"1a");
sort($my_array);
var_dump($my_array);

1b. rsort(array[, sort_type])


SORTING ARRAYS
2a. ksort(array[, sort_type])
SORT_REGULAR
SORT_NUMERIC
SORT_STRING
E.g.
$my_array = array(“first”=>"100a",”second”=>"1a");
sort($my_array);
var_dump($my_array);

2b. krsort(array[, sort_type])


SORTING ARRAYS
3a. asort(array[, sort_type])
SORT_REGULAR
SORT_NUMERIC
SORT_STRING
E.g.
$my_array = array(“first”=>"100a",”second”=>"1a");
sort($my_array);
var_dump($my_array);

3b. arsort(array[, sort_type])


SORTING ARRAYS
4a. usort(array,function])
<?php
function my_sort($a, $b)
{
if ($a == $b) return 0;
return ($a < $b) ? 1 : -1;
}
$arr = array(“Peter”, “glenn”, “Cleveland”, ”peter”, “cleveland”, “Glenn”);
usort($arr, "my_sort");

4b. uksort(array, function)


4c. uasort(array, function)
SORTING ARRAYS
5. array_multisort(array1[,sorting_order, sorting_type], array2[,array3…])
<?php
function my_sort($a, $b)
{
if ($a == $b) return 0;
return ($a < $b) ? 1 : -1;
}
$arr = array(“Peter”, “glenn”, “Cleveland”, ”peter”, “cleveland”, “Glenn”);
usort($arr, "my_sort");

<?php
$ar = array(
array("10", 11, 100, 100, "a"),
array( 1, 2, "2", 3, 1)
);
array_multisort($ar[0], SORT_ASC, SORT_STRING,
$ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>
ITERATING THROUGH ARRAYS
1. current()
2. next()
3. prev()
4. end()
5. reset()
6. each()
ITERATING THROUGH ARRAYS
<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport); // $mode = 'foot';
$mode = end($transport); // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';

$arr = array();
var_dump(current($arr)); // bool(false)

$arr = array(array());
var_dump(current($arr)); // array(0) { }
?>
ITERATING THROUGH ARRAYS
<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>
<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
?>
WORKING WITH DATE/TIME
1. time() : Returns the current time, in the number of SECONDS, since Unix
epoch(January 1 1970 00:00:00 GMT). The no. of seconds that have elapsed
since the UNIX epoch is called a time stamp.

2. microtime([bool getAsFloat = false])

3. strtotime() : parses an English textual date/time to a UNIX timestamp


Parses an English textual date or time into a Unix timestamp (the number of
seconds since January 1 1970 00:00:00 GMT).
echo(strtotime("now") . "<br />");
echo(strtotime(“29 July 2017") . "<br />");
echo(strtotime("+5 hours") . "<br />");
echo(strtotime("+1 day") . "<br />");
echo(strtotime("+1 week 5 days 3 hours 12 seconds") . "<br />");
echo(strtotime("next Thursday") . "<br />");
echo(strtotime("last Sunday"));
WORKING WITH DATE/TIME
4. date(format[, timestamp]) :
d 1 to 31
D A textual representation(first three letters)
m 1 to 12
M A textual representation(first three letters)
y Two digit representation
Y Four digits
h 12 - hour format of an hour
H 24 – hour format of an hour
i Minutes
s Seconds
echo date("Y/m/d")
WORKING WITH DATE/TIME
5. checkdate(month, day, year) :
1<=month<=12
1<=day<=(28 or 29 or 30 or 31)
1<=year<=32767

6. date_default_timezone_get() : returns the default timezone

7. getdate() : Returns an array that contains date and time information for a
Unix timestamp. The returning array contains ten elements with relevant
information needed when formatting a date string:
Key Description

seconds seconds
minutes minutes
hours hours
mday day of the month
wday day of the week
year year
yday day of the year
weekday name of the weekday
month name of the month
WORKING WITH DATE/TIME
8. mktime(hour,minute,second,month,day,year,is_dst) – returns a UNIX
timestamp for a date
hour Optional
minute Optional
second Optional
month Optional. Specifies the numerical month
day Optional. Specifies the numerical day of the month
year Optional.
is_dst Optional. Set this parameter to 1 if the time is during daylight savings
time (DST), 0 if it is not, or -1 (the default) if it is unknown. If it's
unknown, PHP tries to find out itself (which may cause unexpected
results). This parameter became deprecated in PHP 5. The new
timezone handling features should be used instead.

echo date("D-M-Y", mktime(0,0,0,3,15,2012));


STRING FUNCTIONS

1. chr(ascii)

2. chunk_split(string[, length, end])


E.g. echo chunk_split(“Hello World!”,3,”*”);

3. explode(separator, string)
E.g. $arr = explode(“ “,$name);

4. implode([separator,] array)
Default separator is “”

5. htmlentities(string) – converts characters to HTML entities


STRING FUNCTIONS

6. ltrim(), rtrim(), trim()


trim($str[, charlist])
charlist – specifies which chars. to remove from the string
E.g.
$input=" sdfsf \n";
echo trim($input,'\n');

7. similar_text(string1, string2[, percent])


Returns the no. of matching characters.
Percent : similarity in percent
E.g.
similar_text("Hello World","Hello Peter",$percent);
echo $percent;
STRING FUNCTIONS

8. str_replace() and str_ireplace()


str_replace(find, replace, string[, count])
count – stores the no. of characters replaced

str_ireplace() : case – INSENSITIVE search

9. str_repeat(string, repeat)
echo str_repeat(“-”,28);

10. str_shuffle(string)

11. str_split(string[, length]) : splits the string into an array


Default for length is 1. It specifies the length of each array element.
STRING FUNCTIONS

12. strcmp(string1, string2) and strcasecmp(string1, string2)

13. str_word_count(string[, return, char])


return :
0 - Default. Returns the number of words found
1 - Returns an array with the words from the string
2 - Returns an array where the key is the position of the word in the string,
and value is the actual word
char – special characters to be considered as words

print_r(str_word_count("Hello world & good morning!",2,"&"));


STRING FUNCTIONS

14. strip_tags(string[, allow])


echo strip_tags("Hello <b><i>world!</i></b>","<b>");

15. strpos(string, find[, start]) and stripos()


echo strpos("Hello world!","wo");
stripos- case insensitive search

16. strstr(string, search) and stristr()


echo stristr("Hello world!","WORLD");
Finds the first occurrence and returns the rest of the string.
STRING FUNCTIONS
17. printf(format, arg1[, arg2, arg++])
%% - returns a percent sign
%b – binary
%c - The character according to the ASCII value
%d - Signed decimal number
%e - Scientific notation (e.g. 1.2e+2)
%u - Unsigned decimal number
%f - Floating-point number (local settings aware)
%F - Floating-point number (not local settings aware)
%o - Octal number
%s – String
%x - Hexadecimal number (lowercase letters)
%X - Hexadecimal number (uppercase letters)
STRING FUNCTIONS
18. number_format(number[, decimals, decimalpoint, separator])
number: the no. to be formatted
decimals: Optional. Specifies how many decimals
decimalpoint: specifies what string to use as decimal point
separator: specifies what string to use for thousands separator
E.g.
<?php
echo number_format("1000000");
echo "<br />";
echo number_format("1000000",2);
echo "<br />";
echo number_format("1000000",2,",",".");
?>
The output of the code above will be:
1,000,000
1,000,000.00
1.000.000,00
STRING FUNCTIONS

19. strlen(string)

20. strrev(string)

21. substr(string, start[, length])


echo substr(“SICSR BBA(IT)",6);

22. strtolower(string)

23. strtoupper(string)

24. ucfirst(string)

25. ucwords(string)

You might also like