BCA Notes PHP
BCA Notes PHP
BCA Notes PHP
• PHP
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;
function tenTimes()
{
$number = $number * 10;
}
tenTimes();
print $number;
• Associative Arrays
- Creation
- Accessing elements
- Unique keys
- Quotes
• Appending
- key can be <0
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);
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);
$capitals = array(
'USA' => 'Washington',
'Great Britain' => 'London',
'New Zealand' => 'Wellington',
'Australia' => 'Canberra',
'Italy' => 'Rome');
$person = array('name' => ‘Mark’, 'age' => ’35’, ‘place' => ‘India’);
extract($person);
10. compact()
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)
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));
?>
<?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.
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.
1. chr(ascii)
3. explode(separator, string)
E.g. $arr = explode(“ “,$name);
4. implode([separator,] array)
Default separator is “”
9. str_repeat(string, repeat)
echo str_repeat(“-”,28);
10. str_shuffle(string)
19. strlen(string)
20. strrev(string)
22. strtolower(string)
23. strtoupper(string)
24. ucfirst(string)
25. ucwords(string)