UNIT III Open Source Programming Languages - PHP

Size: px
Start display at page:

Download "UNIT III Open Source Programming Languages - PHP"

Transcription

1 UNIT III Open Source Programming Languages - PHP

2 Introduction First started by Rasmus Lerdorf naming PHP/FI called Personal Homepage Tools / Form Interpreter in In 1997 came with PHP/FI2, looking for a language to develop an e-commerce solution. Zeev and Andi decided to completely rewrite the scripting language named as PHP3 called Hypertext Preprocessor in PHP3 support tasks such as accessing databases, spell checkers and others. In late 1998, PHP4 came with a new paradigm of Compile First, Execute Later. The compilation step does not compile PHP scripts into machine code, it instead compile them into byte code, which is then executed by the Zend engine ( stands for Ze ev & a nd i). PHP 4 officially released on May 22, PHP 5 came with the idea of Object Oriented features. Multiple Inheritance was dropped in favor of interfaces. PHP_VERSION is the constant used to identify the current working version of PHP.

3 Define PHP PHP is a server-side scripting language that allows your Web site to be truly dynamic. 1. PHP stands for Hypertext Preprocessor. 2. Its flexibility and relatively small learning curve (especially for programmers who have a background in C, Java, or Perl) make it one of the most popular scripting languages around. 3. PHP s popularity continues to increase as businesses, and individuals everywhere embrace it as an alternative to Microsoft s ASP language and realize that PHP s benefits most certainly outweigh the costs (three cheers for open source!). 4. PHP is a server-side scripting language, which can be embedded in HTML or used as a standalone binary. 5. PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) Variables - Naming Rules for Variables The main way to store information in the middle of a PHP program is by using a variable ways to name and hang on to any value that you want to use later. Here are the most important things to know about variables in PHP: 1. All variables in PHP are denoted with a leading dollar sign ($). 2. The value of a variable is the value of its most recent assignment. 3. Variables are assigned values with the = operator. 4. Variables can, but do not need, to be declared before assignment. 5. Variables have no intrinsic type other than the type of their current value. 6.Variable name must start with a letter or underscore and contain alphanumeric characters. It should not contain the spaces.

4 PHP is a Loosely Typed Language Justify you answer 1. In PHP, a variable does not need to be declared before adding a value to it. 2. In the example below, you see that you do not have to tell PHP which data type the variable is. $a=10; 3. PHP automatically converts the variable to the correct data type, depending on its value. 4. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it. 5. In PHP, the variable is declared automatically when you use it. Basic PHP Syntax A PHP scripting block always starts with and ends with. A PHP scripting block can be placed anywhere in the document. On servers with shorthand support enabled you can start a scripting block with <? and end with. It uses echo and print statement for displaying the output. echo welcome to PHP ; print welcome to CCET ;

5 What can PHP do? PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more. There are three main areas where PHP scripts are used. Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your clientside applications you can also use PHP-GTK to write such programs.

6 Variables 1. Variables are temporary place holders used to represent values used in a PHP script. 2. PHP includes two main types of variables: scalar and array. 3. Scalar variables contain only one value at a time, and array variables contain a list of values. Assigning variables Variable assignment is simple just write the variable name, and add a single equal sign (=); then add the expression that you want to assign to that variable: $var_name = value; $pi = ; approximately Note that what is assigned is the result of evaluating the expression, not the expression itself. After the preceding statement is evaluated, there is no way to tell that the value of $pi was created by adding two numbers together. It s conceivable that you will want to actually print the preceding math expression rather than evaluate it. You can force PHP to treat a mathematical variable assignment as a string by quoting the expression: $pi = ;

7 Reassigning variables There is no interesting distinction in PHP between assigning a variable for the first time and changing its value later. This is true even if the assigned values are of different types. For example, the following is perfectly legal: $my_num_var = This should be a number hope it s reassigned ; $my_num_var = 5; If the second statement immediately follows the first one, the first statement has essentially no effect. Unassigned variables Many programming languages will object if you try to use a variable before it is assigned; others will let you use it, but if you do may find yourself reading the random contents of some area of memory. In PHP, the default error-reporting setting allows you to use unassigned variables with errors, and PHP ensures that they have no reasonable default values. Default values Variables in PHP do not have intrinsic types a variable does not know in advance whether it will be used to store a number or a string of characters. So how does it know what type of default value to have when it hasn t yet been assigned? The answer is that, just as with assigned variables, the type of a variable is interpreted depending on the context in which it is used. In a situation where a number is expected, a number will be produced, and this works similarly with character strings

8 Checking assignment with IsSet Because variables do not have to be assigned before use, in some situations you can actually convey information by selectively setting or not setting a variable. PHP provides a function called IsSet that tests a variable to see whether it has been assigned a value. As the following code illustrates, an unassigned variable is distinguishable even from a variable that has been given the default value: $set_var = 0; //set_var has a value $never_set; //never_set does not have value print( set_var print value: $set_var<br> ); print( never_set print value: $never_set<br> ); if ($set_var == $never_set) print( set_var is equal to never_set!<br> ); if (IsSet($set_var)) print( set_var is set.<br> ); else print( set_var is not set.<br> ); if (IsSet($never_set)) print( never_set is set.<br> ); else print( never_set is not set. );

9 Constant variable: In addition to variables, which may be reassigned, PHP offers constants, which have a single value throughout their lifetime. Constants do not have a $ before their names, and by convention the names of constants usually are in uppercase letters. Constants can contain only scalar values (numbers and string). Constants have global scope, so they are accessible everywhere in your scripts after they have been defined even inside functions. For example, the built-in PHP constant E_ALL represents a number that indicates to the error_reporting() function that all errors and warnings should be reported. A call to error_reporting() might look like this: error_reporting(e_all); This is identical to calling error_reporting () on the integer value of E_ALL, but is better because the actual value of E_ALL may change from one version of PHP to the next. It s also possible to create your own constants using the define () form, although this is more unusual than referring to built-in constants. The code: define( MY_ANSWER, 42); echo(my_answer); echo constant( MY_ANSWER ); _FILE_ returns the name of the file currently being read by the interpreter. _LINE_ returns the line number of the file. PHP_VERSION used to find out the version of PHP by using echo (PHP_VERSION);

10 would cause MY_ANSWER to evaluate to 42 everywhere it appears in your code. There is no way to change this assignment after it has been made, and like variables, constants that are not part of PHP itself do not persist across pages unless they are explicitly passed to a new page. Ultimately, you probably will not need to define constants very often, if ever. When created constants are used, they are generally most usefully defined in an external include file and might be used for such information as a sales-tax rate or perhaps an exchange rate. DATA TYPES PHP has a total of eight types: integers, doubles, Booleans, strings, arrays, objects, NULL, and resources. Integers are whole numbers, without a decimal point, like 495. Doubles are floating-point numbers, like or Booleans have only two possible values: TRUE and FALSE. NULL is a special type that only has one value: NULL. Strings are sequences of characters, like PHP 4.0 supports string operations. Arrays are named and indexed collections of other values. Objects are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class. Resources are special variables that hold references to resources external to PHP (such as database connections). Of these, the first five are simple types, and the next two (arrays and objects) are compound the compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.

11 PHP's scalar data types Scalar data is data that only contains a single value. As of version 6, PHP features 6 scalar data types: Type Description Example values integer A whole number 7, -23 float A floating point number 7.68, string A sequence of characters "Hello", "abc123@#$" unicode A sequence of Unicode characters Encoding Scheme" binary A sequence of binary (non-unicode) characters 0 s and 1 s" boolean Either true or false true, false

12 PHP's compound data types Compound data can contain multiple values. PHP has 2 compound data types: array object Can hold multiple values indexed by numbers or strings Can hold multiple values (properties), and can also contain methods (functions) for working on properties An array or object can contain multiple values, all accessed via one variable name. What's more, those values can themselves be other arrays or objects. This allows you to create quite complex collections of data. PHP's special data types As well as scalar and compound types, PHP has 2 special data types that don't fall into the other categories: resource null Used to access an external resource (for example, a file handle or database connection) Can only contain the value null, which means "no value"

13 Finding out the data type of a value You can check a value's data type using one of the following PHP functions: is_int( value ) is_float( value ) is_string( value ) is_unicode( value ) is_binary( value ) is_bool( value ) is_array( value ) is_object( value ) is_resource( value ) is_null( value ) Returns true if value is an integer, false otherwise Returns true if value is a float, false otherwise Returns true if value is a string, false otherwise Returns true if value is a Unicode string, false otherwise Returns true if value is a binary string, false otherwise Returns true if value is a Boolean, false otherwise Returns true if value is an array, false otherwise Returns true if value is an object, false otherwise Returns true if value is a resource, false otherwise Returns true if value is null, false otherwise

14 Changing data types with settype() PHP has a function called settype() that converts a variable's value from one data type to another: $x = 3.14; settype( $x, "integer" ); echo $x; In the above example, $x's data type is changed from float to integer (with the result that $x ends up containing the value 3). Be careful when changing data types, since you may end up losing information for example, when changing a float (3.14) to an integer (3). Changing data types with casting If you just want to change a value's type at the time you use the value, then you can use casting. This merely changes the type of the value that is to be used; the original variable remains untouched. To cast a value, place the data type in parentheses before the value at the time you use it: $x = 3.14;echo (integer) $x; The above code displays 3 (3.14 cast to an integer). However, note that $x still contains the value 3.14 after the cast operation. You can, if you prefer, use (int) instead of (integer), and (bool) instead of (boolean).

15 Below, we have an example of a simple PHP script which sends the text "Hello World" to the browser: <html> <body> </body> </html> // Example for Simple PHP echo"helloworld"; Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World".

16 String Variables: Below, the PHP script assigns the text "Hello World" to a string variable called $txt: $txt="hello World"; echo $txt; The output of the code above will be: Hello World Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two string variables together, use the concatenation operator: $txt1="hello World!"; $txt2= Have a nice day!"; echo $txt1. " ". $txt2; The output of the code above will be: Hello World! Have a nice day!

17 The strlen() function The strlen() function is used to return the length of a string. Let's find the length of a string: echo strlen("hello world!"); The output of the code above will be:12 The strpos() function The strpos() function is used to search for character within a string. If a match is found, this function will return the position of the first match. If no match is found, it will return FALSE. Let's see if we can find the string "world" in our string: echo strpos("hello world!","world"); The output of the code above will be:6

18 OPERATORS 18

19 PHP supports a rich set of operators. Arithmetic operators Relational operators Logical operators Assignment operators Increment and Decrement operators Conditional operators Bitwise logical operators ARITHMETIC OPERATORS Operator Meaning + Addition or Unary plus - Subtraction or Unary Minus * Multiplication / Division % Modulo Division Integer Arithmetic $a % $b equivalent to $a ( $a / $b ) * $b Real Arithmetic -14 % 3 = % -3 = % -3 = 2 Mixed Mode Arithmetic Ex: 15 / 10.0 produces the result

20 RELATIONAL OPERATOR LOGICAL OPERATOR Operator Meaning < Is less than <= Is less than or equal to > Is greater than >= Is greater than or equal to == Is equal to!= Is not equal to Operator Meaning && Logical AND Logical OR! Logical NOT BITWISE LOGICAL OPERATOR PHP supports operators that may be used for manipulation of data at bit level. These operators may be used for testing the bits or shifting them to the right or left. Bitwise operators may not be applied to floating point data. Operator Meaning & Bitwise Logical AND Bitwise Logical OR ^ Bitwise Logical XOR ~ One s Complement << Left Shift >> Right Shift 20

21 Bitwise Complement ( ~ ) Variable Value Binary Pattern X ~X Y FF ~Y Shift Operations Left Shift Variable Value Binary Pattern $X (8 bits) $X << 3 the bit pattern of $X value is left shifted by thrice The Resultant bit pattern will be

22 Right Shift Variable Value Binary Pattern $Y $Y>>3 the bit pattern of the $Y value is right shifted by thrice The Resultant bit pattern will be Bitwise Logical AND Variable Value Binary Pattern $X $Y $X & $Y $A $B $A & $B Bitwise Logical OR Variable Value Binary Pattern $X $Y $X $Y $A $B $A & $B Bitwise Exclusive OR Variable Value Binary Pattern $X $Y $X ^ $Y $A $B $A ^ $B

23 Assignment Operator Assignment operators are used to assign the value of an expression to a variable. PHP has a set of shorthand assignment operators which are used in the form v op= exp v - is the variable exp - is the expression op - is the binary operator v op= exp is equivalent to v = v op(exp); Ex: $x + = $y + 1; is equivalent to $x = $x + ($y +1) Advantages:. What appears on the left hand side need not be repeated and therefore it becomes easier to write.. The statement is more concise and easier to read.. The use of shorthand operators results in a more efficient code. 23

24 Increment and Decrement Operator The operators are ++ and means Increment Operator - - means Decrement Operator The operator ++ adds 1 to the operand while subtracts 1. Both are unary operators and are used in the following form: $++m; or $m++ $--m or $m-- $++m; is equivalent to $m = $m + 1 (or $m + = 1;) $--m; is equivalent to $m = $m 1 (or $m - = 1;) We use the increment and decrement operators extensively in for and while loops For Example: Case 1 $m = 5; $y = $++m; Case 2 $m = 5; $y = $m--; The statement $a [$ i ++ ] = 10; is equivalent to $a [$ i ] = 10; $i = $i + 1; 24

25 DECISION MAKING BRANCHING and LOOPING Or CONTROL STRUCTURE 25

26 Decision making with IF statement 1. Simple if statement 2. if else statement 3. Nested if else statement 4. else if ladder Simple if statement if (Boolean-expression) Statement-block Statement x if else statement if (Boolean-expression) True-block statement(s) else Flase-block statement(s) Statement-x; 26

27 Example Simple if statement $a = 10; if($a % 2 == 0) echo "The given no is Even No."; if else statement $a = 10: if ($a % 2 == 0) echo The Given no is Even No. ; else echo The Given no is Odd No. ;

28 Nesting if else statement if (Boolean-expression) True-block statement(s) if (Boolean-expression) True-block Statement(s) else False-block Statement(s) else False-block statement(s) 28

29 Nesting if else statement Example $a = 23; $b = 78; $c = 76; if ($a > $b) if ($a > $c) echo The A is Biggest Number ; else echo The C is Biggest Number ; else if($b > $c) echo The B is Biggest Number ; else echo The C is Biggest Number ; 29

30 else if Ladder if (condition_1) Statement_1; else if (condition_2) Statement_2; else if (condition_3) else Default-Statement-x; Statement_3;... else if (condition_n) Statement_n; 30

31 else if Ladder Example $average = 67; if($average >= 80) echo First Class with Distinction ; else if($average >= 60 && $average < 80) echo First Class ; else echo No Grade ; else if($average >= 50 && $average < 60) echo Second Class ; 31

32 THE SWITCH STATEMENT switch (expression) case value_1: Statement_x; case value_2: case value_3: default: block_1; break; block_2; break; block_3; break; default_block break; 32

33 $a = 10; $b = 50; echo "Select your Choice"; echo "Addition"; echo "Subtraction"; echo "Multiplication"; echo "Division"; $choice = "Multiplication"; switch($choice) case "Addition": $c = $a + $b; echo "Addition of the Two Numbers:",$c; break; case "Subtraction": $c = $a - $b; echo "Subtraction of the Two Numbers:",$c; break;

34 case "Multiplication": $c = $a * $b; echo "Multiplication of the Two Numbers:",$c; break; case "Division" $c = $a / $b; echo "Division of the Two Numbers:",$c; break; default: echo "Invalid Your Choice"; break; DECISION MAKING AND LOOPING The PHP provides for six constructs for performing loop operations. They are: 1. The while statement 2. while.endwhile statement 3. The do while statement 4. The for statement 5. for.endfor statement 6. foreach statement

35 The while statement Syntax: initialization; while(test_condition) Body of the Loop The do statement Syntax: initialization do Body of the Loop while (test_condition); The while endwhile statement Syntax: initialization; while(test_condition): Body of the Loop endwhile; The for statement Syntax: for (initialization;test_condition;increment) Body of the Loop 35

36 The for endfor statement Syntax: for (initialization;test_condition;increment): Body of the Loop endfor; The foreach statement Syntax: foreach(expression_1 as expression_2) statement; The while statement Example $n = 10; $i = 1; while($i <= $n) echo "The I Value is:",$i; $i++; The do while statement Example $n = 10; $i = 1; do echo "The I Value is:",$i; $i++; while($i <= $n);

37 The while endwhile statement Example $n = 10; $i = 1; while($i <= $n): echo "The I Value is:",$i; $i++; endwhile; The for statement $n = 10; for($i = 1;$i <= $n;$i++) echo "The I Value is:",$i; The for endfor statement $n = 10; for($i = 1;$i <= $n;$i++): echo "The I Value is:",$i; endfor;

38 Additional Features of the for Loop Case 1: $p = 1; for ($n = 0; $n<17;$n++) can be rewritten as for ($p=1,$n=0;$n<17;$n++) Case 2: for ($n=1,$m=50;$n<=$m; $n=$n+1,$m=$m-1) Case 3: $sum = 0; for($i =1, $i<20 && $sum <100; $i++) Case 4: for ($x = ($m+$n)/2; $x>0;$x = $x/2) Case 5: $m = 5; for (;$m!= 100;) echo The M Value is:,$m; $m = $m + 5; Case 6: for ($j = 1000; $j>0; $j =$ j 1); 38

39 Jumps in Loops break; continue; break Statement $n = 10; $i = 1; while($i < $n) echo "<br>the I Value is:",$i; if($i == 5) echo "<br>the I Value is Equal to 5, so Exit the Loop"; break; $i++; 39

40 continue Statement $n = 10; $i = 1; while($i < $n) echo "<br>the I Value is:",$i; if($i == 5) echo "<br>the I Value is Equal to 5, so Exit the Loop"; continue; $i++;

41 Array

42 PHP ARRAY Create a PHP Array 1.Arrays are created using the array() function. 2.The array() function takes zero or more arguments and returns the new array which is assigned to a variable using the assignment operator (=). 3.If arguments are provided they are used to initialize the array with data. 4.PHP arrays grow and shrink dynamically as items are added and removed so it is not necessary to specify the array size at creation time as it is with some other programming languages. 5.We can create an empty array as follows: $colorarray = array(); 6.Alternatively, we can create an array pre-initialized with values by providing the values as arguments to the array() function: $colorarray = array("red", "Yellow", "Green", "Blue", "Indigo");

43 Types of Array 1. Numeric Array 2. Associative Array 3. Multi Dimensional Array 1. Numeric Array The elements in a PHP numerical key type array are accessed by referencing the variable containing the array, followed by the index into array of the required element enclosed in square brackets ([]). We can extend our previous example to display the value contained in the second element of the array (remember that the index is zero based so the first element is element 0): $numberarray = array(10, 20, 30, 40, 50, 60, 70, 80, 90, 100); echo $numberarray[1]; The above echo command will output the value in index position 1 of the array, in this case the Number is 20.

44 Example: $cars=array("saab","volvo","bmw","toyota"); echo $cars[0]. " and ". $cars[1]. " are Swedish cars."; The output is: Saab and Volvo are Swedish Cars. In the above example we assign the index manually: $cars[0]="saab"; $cars[1]="volvo"; $cars[2]="bmw"; $cars[3]="toyota"; The above program can also written as: $cars[0]="saab"; $cars[1]="volvo"; $cars[2]="bmw"; $cars[3]="toyota"; echo $cars[0]. " and ". $cars[1]. " are Swedish cars.";

45 Print the Array Element using foreach looping Statement $number = array(10,20,30,40,50,60,70,80,90,100); foreach($number as $n) echo The Array Element is:,$n; What are the advantages of for loop statement over the foreach statements? The advantage of foreach over the for statement is that it automatically detects the boundaries of the collection being iterated over. Further, the syntax includes a built in iterator for accessing the current element in the collection.

46 Associative Array An associative array assigns names or ID key to positions in the array. This provides a more human friendly way to access array elements than the numerical key approach. Once again, the array() function is used to create the array, with optional arguments to preinitialize the array elements. In the case of associative arrays, the arguments are of the form key=>value where key is the name by which the element will be referenced, and value is the value to be stored in that position in the array. $customerarray = array('customername'=>'john Smith', 'customeraddress'=>'1 The Street', 'accountnumber'=>' ); echo $customerarray['customername']; $ages = array("peter"=>32, John"=>30, "Joe"=>34); echo "Peter is ". $ages['peter']. " years old."; The output is : Peter is 32 years old. $ages['peter'] = "32"; $ages[ John'] = "30"; $ages['joe'] = "34"; echo "Peter is ". $ages['peter']. " years old.";

47 Multidimensional PHP Arrays A multidimensional PHP array is nothing more than an array in which each array element is itself an array. A multidimensional array can, therefore, be thought of as a table, where each element in the parent array represents a row of the table and the elements of each child array represent the columns of the row. $dept=array( echo $dept[ CSE ][2]; ); CSE"=>array ( Development", Networking", Testing" ), IT"=>array ( Designing" ), ECE"=>array ( VLSI", Embedded" )

48 $books = array(); $books[0] = array('title'=>'javascript in 24 Hours', 'author'=>'moncur'); $books[1] = array('title'=>'javascript Unleashed', 'author'=>'wyke'); $books[2] = array('title'=>'network+ Second Edition', 'author'=>'harwood'); echo $books[1]['author']; The echo will output "Wyke" which is in the author column of the second row of the array. What is a PHP Function? Functions are basically named scripts that can be called upon from any other script to perform a specific task. Values (known as arguments) can be passed into a function so that they can be used in the function script, and functions can, in turn, return results to the location from which they were called.

49 How to Write a PHP Function The first step in creating a PHP function is to provide a name by which you will reference the function. Naming conventions for PHP functions are the same as those for variables in that they must begin with a letter or an underscore and must be devoid of any kind of white space or punctuation. You must also take care to ensure that your function name does not conflict with any of the PHP built in functions. PHP functions are created using the function keyword followed by the name and, finally, a set of parentheses. The body of the function (the script that performs the work of the function) is then enclosed in opening and closing braces. The following example function simply outputs a string when it is called: function sayhello() print "Hello";

50 Returning a Value from a PHP Function A single value may be returned from a PHP function to the script from which it was called. The returned value can be any variable type of your choice. The return keyword is used to return the value: function returnten () return 10; echo returnten(); The above example returns the value of 10 to the calling script. Passing Parameters to a PHP Function Parameters (or arguments as they are more frequently known) can be passed into a function. There are no significant restrictions of the number of arguments which can be passed through to the function. A function can be designed to accept parameters by placing the parameter names inside the parentheses of the function definition. There are no specific rules on the names that can be given to these arguments other than those applying to variable names in general. In the following examples we will use $arg1 and $arg2 as argument variable names. These variables can then be accessed using the assigned names from within the function body as follows:

51 function addnumbers ($arg1, $arg2) return $arg1 + $arg2; echo addnumbers(10,20); In the above example the addnumbers() function accepts two parameters as arguments assigned to variables arg1 and arg2 respectively, adds them together and returns the result. Calling PHP Functions PHP functions are called by using the name declared when the function was defined, together with any values that need to be passed through as parameters. The following example both defines and then calls our addnumbers() function: function addnumbers ($arg1, $arg2) return $arg1 + $arg2; $var1 = 10; $var2 = 20; print addnumbers( $var1, $var2); When loaded into a browser the print statement will display the result returned by the addnumbers() function, in this case the number 30.

52 Passing Parameters by Reference function addnumbers (&$arg1, &$arg2) $arg1 += 10; $arg2 += 10; return $arg1 + $arg2; $var1 = 10; $var2 = 20; echo "Before Calling..$var1+ $var2.. <br>"; echo "After Calling.. addnumbers($var1,$var2);

53 CLASS FUNDAMENTALS

54 BASIC CONCEPT OF THE PHP OBJECT ORIENTED PROGRAMMING 1. Class 2. Object 3. Data Encapsulation 4. Data Hiding 5. Polymorphism 6. Inheritance 7. Inheritance with Abstract Class 8. Inheritance with Method Overriding 9. Inheritance with final keyword 10. Interface 11. Interface implements to the class 12. Interface implements to the Abstract class

55 The General Form of a Class When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data. While very simple classes may contain only code or only data, most real-world classes contain both. As you will see, a class code defines the interface to its data. A class is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. Classes can (and usually do) get much more complex. The general form of a class definition is shown here: class classname access specifier instance-variable1; access specifier instance-variable2; //... access specifer instance-variablen; function methodname1(parameter-list) // body of method function methodname2(parameter-list) // body of method //... function methodnamen(parameter-list) // body of method

56 Class and Object class Example private $a; private $b; private $c; function initialize() $this->a = 89; $this->b = 78; function addition() $this->c = $this->a + $this->b; function printdata() echo "Addition of the Two Numbers:",$this->c; $ex = new Example(); $ex->initialize(); $ex->addition(); $ex->printdata();

57 Class and Object Call by Value Mutator class Example private $a; private $b; private $c; function initialize($x,$y) $this->a = $x; $this->b = $y; function addition() $this->c = $this->a + $this->b; function printdata() echo "Addition of the Two Numbers:",$this->c; $ex = new Example(); $ex->initialize(78.67,45.43); $ex->addition(); $ex->printdata();

58 Class and Object Call by Value Mutator Return value class Example private $a; private $b; private $c; function initialize($x,$y) $this->a = $x; $this->b = $y; function addition() $this->c = $this->a + $this->b; return $this->c; $ex = new Example(); $ex->initialize(78.67,45.43); $add = $ex->addition(); echo The Addition of the Two Numbers:,$add;

59 Parameterless Constructor or Default Constructor class Example private $a; private $b; private $c; function _construct() $this->a = 78; $this->b = 45; function addition() $this->c = $this->a + $this->b; function printdata() echo "Addition of the two Numbers:",$this->c; $ex = new Example(); $ex->addition(); $ex->printdata();

60 Parameterized Constructor class Example private $a; private $b; private $c; function _construct($x,$y) $this->a = $x; $this->b = $y; function addition() $this->c = $this->a + $this->b; function printdata() echo "Addition of the two Numbers:",$this->c; $ex = new Example(34.56,78.43); $ex->addition(); $ex->printdata();

61 Constructor and Destructor class Example private $a; private $b; private $c; function _construct() echo The Initialized value memory was Allocated ; function _destruct() echo The Initialized value memory was Deallocated ; function printdata() echo This is the Constructor and Destructor Example ; $ex = new Example(); $ex->printdata();

62 INHERITANCE

63 INHERITANCE What is Inheritance? Inheritance is the mechanism which allows a class B to inherit properties/characteristicsattributes and methods of a class A. We say B inherits from A". A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class What are the Advantages of Inheritance 1. Reusability of the code. 2. To Increase the reliability of the code. 3. To add some enhancements to the base class.

64 Inheritance achieved in two different forms 1. Classical form of Inheritance 2. Containment form of Inheritance Classical form of Inheritance A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class We can now create objects of classes A and B independently. Example: A a; //a is object of A B b; //b is object of B

65 In Such cases, we say that the object b is a type of a. Such relationship between a and b is referred to as is a relationship Example 1. Dog is a type of animal 2. Manager is a type of employee 3. Ford is a type of car Animal Horse Dog Lion

66 Containment Inheritance We can also define another form of inheritance relationship known as containership between class A and B. Example: class A class B B b; A a; // a is contained in b

67 In such cases, we say that the object a is contained in the object b. This relationship between a and b is referred to as has a relationship. The outer class B which contains the inner class A is termed the parent class and the contained class A is termed a child class. Example: 1. car has a radio. 2. House has a store room. 3. City has a road. Car object Radio object

68 Types of Inheritance 1. Single Inheritance (Only one Super Class and One Only Sub Class) 2. Multilevel Inheritance (Derived from a Derived Class) 3. Hierarchical Inheritance (One Super Class, Many Subclasses) 1. Single Inheritance (Only one Super Class and Only one Sub Class) A B

69 2. Multilevel Inheritance (Derived from a Derived Class) A B 4. Hierarchical Inheritance (One Super class, Many Subclasses) C A B C D

70 Single Inheritance class Base_Example protected $a; protected $b; protected $c; function Initialize() $this->a = 78.56; $this->b = 87.34; class Derived_Example extends Base_Example function printdata() $this->c = $this->a + $this->b; echo "Addition of the Two Numbers:",$this->c; $de = new Derived_Example(); $de->initialize(); $de->printdata();

71 Multilevel Inheritance class Base_Example protected $a; protected $b; protected $c; function Initialize() $this->a = 78.56; $this->b = 87.34; class Derived_Example_1 extends Base_Example function process() $this->c = $this->a + $this->b;

72 class Derived_Example_2 extends Derived_Example_1 function printdata() echo "Addition of the Two Numbers:",$this->c; $de = new Derived_Example_2(); $de->initialize(); $de->process(); $de->printdata();

73 Hierarchical Inheritance class Base_Example protected $a; protected $b; protected $c; function Initialize() $this->a = 78.56; $this->b = 87.34; class Derived_Example_1 extends Base_Example function Addition() $this->c = $this->a + $this->b; echo "Addition of the Two Numbers:",$this->c;

74 class Derived_Example_2 extends Base_Example function Subtraction() $this->c = $this->a - $this->b; echo "Subtraction of the Two Numbers:",$this->c; $de_1 = new Derived_Example_1(); $de_1->initialize(); $de_1->addition(); $de_2 = new Derived_Example_2(); $de_2->initialize(); $de_2->subtraction();

75 Inheritance with Abstract Class

76 Abstract Class You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super class. Thus, a subclass must override them it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form: abstract function func_name (parameter list); Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. Conditions for the Abstract Class 1. We cannot use abstract classes to instantiate objects directly. For example. Shape s = new Shape(); is illegal because shape is an abstract class. 2. The abstract methods of an abstract class must be defined in its subclass. 3. We cannot declare abstract constructors or abstract static methods.

77 Inheritance with Abstract Class abstract class Base_Example protected $a; protected $b; protected $c; function Initialize() $this->a = 78.56; $this->b = 87.34; abstract function Addition(); abstract function Subtraction();

78 class Derived_Example_1 extends Base_Example function Addition() $this->c = $this->a + $this->b; echo "Addition of the Two Numbers:",$this->c; function Subtraction() $this->c = $this->a - $this->b; echo "Subtraction of the Two Numbers:",$this->c; $de_1 = new Derived_Example_1(); $de_1->initialize(); $de_1->addition(); $de_1->subtraction();

79 Inheritance with Method Overriding

80 1. Method overriding means a subclass method overriding a super class method. 2. Superclass method should be non-static. 3. Subclass uses extends keyword to extend the super class. 4. In the example class B is the sub class and class A is the super class. 5. In overriding methods of both subclass and superclass possess same signatures. 6. Overriding is used in modifying the methods of the super class. 7. In overriding return types and constructor parameters of methods should match.

81 Inheritance with Method Overriding abstract class Base_Example protected $a; protected $b; protected $c; function Initialize() $this->a = 78.56; $this->b = 87.34; abstract function Addition(); abstract function Subtraction(); class Derived_Example_1 extends Base_Example function Addition() $this->c = $this->a + $this->b; echo "Addition of the Two Numbers:",$this->c; function Subtraction() $this->c = $this->a - $this->b; echo "Subtraction of the Two Numbers:",$this->c;

82 class Derived_Example_2 extends Derived_Example_1 function Addition() $this->c = $this->a * $this->b; echo "Multiplication of the Two Numbers:",$this->c; function Subtraction() $this->c = $this->a / $this->b; echo "Division of the Two Numbers:",$this->c; $de_2 = new Derived_Example_2(); $de_2->initialize(); $de_2->addition(); $de_2->subtraction();

83 Inheritance with final Keyword Cannot Overriding Method abstract class Base_Example protected $a; protected $b; protected $c; function Initialize() $this->a = 78.56; $this->b = 87.34; abstract function Addition(); abstract function Subtraction(); class Derived_Example_1 extends Base_Example final function Addition() $this->c = $this->a + $this->b; echo "Addition of the Two Numbers:",$this->c; final function Subtraction() $this->c = $this->a - $this->b; echo "Subtraction of the Two Numbers:",$this->c;

84 class Derived_Example_2 extends Derived_Example_1 function Addition() //Cannot Overriding Method $this->c = $this->a * $this->b; echo "Multiplication of the Two Numbers:",$this->c; function Subtraction() //Cannot Overriding Method $this->c = $this->a / $this->b; echo "Division of the Two Numbers:",$this->c; $de_2 = new Derived_Example_2(); $de_2->initialize(); $de_2->addition(); $de_2->subtraction();

85 Inheritance with Method Overriding Cannot Inherit abstract class Base_Example protected $a; protected $b; protected $c; function Initialize() $this->a = 78.56; $this->b = 87.34; abstract function Addition(); abstract function Subtraction(); final class Derived_Example_1 extends Base_Example function Addition() $this->c = $this->a + $this->b; echo "Addition of the Two Numbers:",$this->c; function Subtraction() $this->c = $this->a - $this->b; echo "Subtraction of the Two Numbers:",$this->c;

86 class Derived_Example_2 extends Derived_Example_1 //Cannot Inherit function Addition() $this->c = $this->a * $this->b; echo "Multiplication of the Two Numbers:",$this->c; function Subtraction() $this->c = $this->a / $this->b; echo "Division of the Two Numbers:",$this->c; $de_2 = new Derived_Example_2(); $de_2->initialize(); $de_2->addition(); $de_2->subtraction();

87 Interface

88 Why are you using Interface? 1. As like Java, PHP does not support multiple inheritances. That is, classes in java cannot have more than one superclass. For instances, class A extends B extends C However, the designers of java could not overlook the importance of multiple inheritances. 3. A large number of real life applications require the use of multiple inheritances whereby we inherit methods and properties from several distinct classes. 4. Since C++ like implementation of multiple inheritances proves difficult and adds complexity to the language, Java provides an alternate approach known as interfaces to support the concept of multiple inheritances. 5. Although a java class cannot be a subclass or more than one superclass, it can implement more than one interface, thereby enabling us to create classes that build upon other classes without the problems created by multiple inheritances.

89 Defining Interfaces An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with major difference. The difference is that interfaces define only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contain only constants. Syntax: interface Interface_name Method declaration; Ex: interface Item function display ();

90 How to Interface implements to the Classes Syntax: class class_name implements interface_name //Member of the Classes //Definition of the Interfaces Ex: interface student function print_details(); class Inter_Def implements student function print_details() $slno = 1234; $name = CCET ; echo "The Serial Number is:",$slno; echo The Student name is:",$name; $obj = new Inter_Def(); $obj->print_details();

91 Difference between Abstract Classes and Interfaces Abstract classes Abstract classes are used only when there is a is-a type of relationship between the classes. You cannot extend more than one abstract class. Interfaces Interfaces can be implemented by classes that are not related to one another. You can implement more than one interface. it contains both abstract methods and non Abstract Methods Interface contains all abstract methods Abstract class can implemented some methods also. With abstract classes, you are grabbing away each class s individuality. Interfaces can not implement methods. With Interfaces, you are merely extending each class s functionality.

92 Difference between Classes and Interfaces 1. Interface is little bit like a class... but interface is lack in instance variables...that's u can't create object for it. 2. Interfaces are developed to support multiple inheritances. 3. The methods present in interfaces are pure abstract. 4. The access specifiers public, private, protected are possible with classes. But the interface uses only one specifier public. 5. Interfaces contain only the method declarations... no definitions In Class, the variable declaration as well as initialization, but interface only for declaration..

93 Types of Interfaces A Interface Implementation A Class D Interface B Class Extension B Extension Implementation Class E Extension Interface C Class Extension C Class A Interface Implementation B C Class Class

94 Interface A B Interface Extension C Interface Implementation D Class

95 Interface Implements to the Class interface Add public function addition(); interface Sub public function subtraction(); class Addition implements Add protected $a; protected $b; protected $c; function initialize() $this->a = 89; $this->b = 90; public function addition() $this->c = $this->a + $this->b; echo "Addition of the Two Numbers<br>:",$this->c;

96 class Subtraction implements Sub protected $a; protected $b; protected $c; function initialize() $this->a = 89; $this->b = 90; public function Subtraction() $this->c = $this->a - $this->b; echo "Subtraction of the Two Numbers<br>:",$this->c; $add = new Addition(); $add->initialize(); $add->addition(); $sub = new Subtraction(); $sub->initialize(); $sub->subtraction();

97 PHP and MySQL

98 MySQL Create Database Using PHP $connect = mysql_connect("localhost","root","") or die("could not Connection Established".mysql_error()); $query = "create database student"; $query_result = mysql_query($query) or die("could not be Execute the Query".mysql_error()); echo "The Database was Created"; MySQL Create Tables Using PHP $connect = mysql_connect("localhost","root","") or die("could not be Established the Connection".mysql_error()); $database = mysql_selectdb("student") or die("cannot be Open the Database".mysql_error()); $query = "create table studmark(studid int not null,studname varchar(20),mark1 int not null,mark2 int not null,mark3 int not null,primary key(studid))"; $query_result = mysql_query($query) or die("could not be Execute the Query".mysql_error()); echo "The Table was Created";

99 MySQL Inert Query Using PHP $connect = mysql_connect("localhost","root","") or die("could not be Established the Connection".mysql_error()); $database = mysql_selectdb("student") or die("cannot be Open the Database".mysql_error()); //$query = "insert into studmark value(1001,'aaa',78,89,78)"; //$query = "insert into studmark value(1002,'bbb',67,87,76)"; //$query = "insert into studmark value(1003,'ccc',98,76,65)"; //$query = "insert into studmark value(1004,'ddd',98,65,98)"; $query = "insert into studmark value(1005,'eee',98,87,90)"; $query_result = mysql_query($query) or die("could not be Execute the Query".mysql_error()); echo "One Record was Inserted";

100 MySQL Alter Table Query Using PHP $connect = mysql_connect("localhost","root","") or die("could not be Established the Connection".mysql_error()); $database = mysql_selectdb("student") or die("cannot be Open the Database".mysql_error()); //$query = "alter table studmark add total int not null"; $query = "alter table studmark add average float not null"; $query_result = mysql_query($query) or die("could not be Execute the Query".mysql_error()); echo "Table was altered"; MySQL Update Table Query Using PHP $connect = mysql_connect("localhost","root","") or die("could not be Established the Connection".mysql_error()); $database = mysql_selectdb("student") or die("cannot be Open the Database".mysql_error()); //$query = "update studmark set total = mark1 + mark2 + mark3"; $query = "update studmark set average= total / 3"; $query_result = mysql_query($query) or die("could not be Execute the Query".mysql_error()); echo "Table was Updated";

101 MySQL Select Query Using PHP $connect = mysql_connect("localhost","root","") or die("could not be Established the Connection".mysql_error()); $database = mysql_selectdb("student") or die("cannot be Open the Database".mysql_error()); $query = "select * from studmark"; $query_result = mysql_query($query) or die("could not be Execute the Query".mysql_error()); echo "<table border = 1>"; echo "<tr>"; echo "<th>student ID</th>"; echo "<th>student Name</th>"; echo "<th>mark1</th>"; echo "<th>mark2</th>"; echo "<th>mark3</th>"; echo "<th>total</th>"; echo "<th>average</th>"; echo "</tr>";

102 while($row = mysql_fetch_array($query_result)) echo "<tr>"; echo "<td>$row[studid]</td>"; echo "<td>$row[studname]</td>"; echo "<td>$row[mark1]</td>"; echo "<td>$row[mark2]</td>"; echo "<td>$row[mark3]</td>"; echo "<td>$row[total]</td>"; echo "<td>$row[average]</td>"; echo "</tr>"; MySQL Delete Query Using PHP $connect = mysql_connect("localhost","root","") or die("could not be Established the Connection".mysql_error()); $database = mysql_selectdb("student") or die("cannot be Open the Database".mysql_error()); $query = "Delete from studmark"; $query_result = mysql_query($query) or die("could not be Execute the Query".mysql_error()); echo "The Table Record was Deleted";

103 PHP ERROR HANDLING

104 PHP Error Handling When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. We will show different error handling methods: 1. Simple "die()" statements 2. Custom errors and error triggers 3. Error reporting Basic Error Handling: Using the die () function The first example shows a simple script that opens a text file: $file=fopen("welcome.txt","r"); If the file does not exist you might get an error like this: Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:\webfolder\test.php on line 2 To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it:

105 if(!file_exists("welcome.txt")) die("file not found"); else $file=fopen("welcome.txt","r"); Now if the file does not exist you get an error like this: File not found die Equivalent to exit The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error. However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors. Creating a Custom Error Handler Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP. This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):

106 Syntax error_function(error_level,error_message,error_file,error_line,error_context) Parameter error_level error_message error_file error_line error_context Description Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels Required. Specifies the error message for the user-defined error Optional. Specifies the filename in which the error occurred Optional. Specifies the line number in which the error occurred Optional. Specifies an array that points to the active symbol table at the point the error occurred Error Report levels These error report levels are the different types of error the user-defined error handler can be used for:

107 Value Constant Description 2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted 8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally 256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() 512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() 1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() 4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) 8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

108 Now let s create a function to handle errors: function customerror($errno, $errstr) echo "<b>error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die(); The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script. Now that we have created an error handling function we need to decide when it should be triggered. Set Error Handler - Sets a user-defined error handler function The default error handler for PHP is the built in error handler. We are going to make the function above the default error handler for the duration of the script. It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways. However, in this example we are going to use our custom error handler for all errors: set_error_handler(error_handler, error_types);

109 Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level. Example Testing the error handler by trying to output variable that does not exist: //error handler function function customerror($errno, $errstr) echo "<b>error:</b> [$errno] $errstr"; //set error handler set_error_handler("customerror"); //trigger error echo $test; The output of the code above should be something like this: Error: [8] Undefined variable: test

110 Trigger an Error In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function. Example In this example an error occurs if the "test" variable is bigger than "1": $test=2; if ($test>1) trigger_error("value must be 1 or below"); The output of the code above should be something like this: Notice: Value must be 1 or below in C:\webfolder\test.php on line 6 An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.

111 Possible error types: E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halted E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally Example In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an E_USER_WARNING occurs we will use our custom error handler and end the script: //error handler function function customerror($errno, $errstr) echo "<b>error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die();

112 //set error handler set_error_handler("customerror",e_user_warning); //trigger error $test=2; if ($test>1) trigger_error("value must be 1 or below",e_user_warning); The output of the code above should be something like this: Error: [512] Value must be 1 or below Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging. Error Logging By default, PHP sends an error log to the servers logging system or a file, depending on how the error_log configuration is set in the php.ini file. By using the error_log() function you can send error logs to a specified file or a remote destination. Sending errors messages to yourself by can be a good way of getting notified of specific errors.

113 Syntax: bool error_log ( string $message, int $message_type = 0, string $destination, string $extra_headers ); message message_type - The error message that should be logged. - Says where the error should go. The possible message types are, 0 message is sent to PHP's system logger, 1 message is sent by to the address in the destination parameter. 2 No longer an option. 3 message is appended to the file destination. 4 message is sent directly to the SAPI (Server API) logging handler. Destination extra_headers - The destination. Its meaning depends on the message_type. - The extra headers. It's used when the message_type parameter is set to 1.

114 Send an Error Message by In the example below we will send an with an error message and end the script, if a specific error occurs: //error handler function function customerror($errno, $errstr) echo "<b>error:</b> [$errno] $errstr<br />"; echo "Webmaster has been notified"; error_log("error: [$errno] $errstr",1, "someone@example.com","from: webmaster@example.com"); //set error handler set_error_handler("customerror",e_user_warning); //trigger error $test=2; if ($test>1) trigger_error("value must be 1 or below",e_user_warning);

115 The output of the code above should be something like this: Error: [512] Value must be 1 or below Webmaster has been notified And the mail received from the code above looks like this: Error: [512] Value must be 1 or below This should not be used with all errors. Regular errors should be logged on the server using the default PHP logging system.

116 SENDING AND RECEIVING E MAIL IN PHP

117 Definition and Usage The mail() function allows you to send s directly from a script. This function returns TRUE if the was successfully accepted for delivery, otherwise it returns FALSE. Syntax mail (to, subject, message, headers, parameters) Parameter to subject Description Required. Specifies the receiver / receivers of the Required. Specifies the subject of the . Note: This parameter cannot contain any newline characters message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters headers parameters Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n) Optional. Specifies an additional parameter to the sendmail program

118 PHP Simple The simplest way to send an with PHP is to send a text . In the example below we first declare the variables ($to, $subject, $message, $from, $headers), then we use the variables in the mail () function to send an $to $subject $message $from $headers = "someone@example.com"; = "Test mail"; = "Hello! This is a simple message."; = "someonelse@example.com"; = "From: $from"; mail($to,$subject,$message,$headers); echo "Mail Sent."; PHP Mail Form With PHP, you can create a feedback-form on your website. The example below sends a text message to a specified address: <html> <body> if (isset($_request[' ']))

119 </body></html> //if " " is filled out, send //send $ = $_REQUEST[' '] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail( "someone@example.com", "Subject: $subject", $message, "From: $ " ); echo "Thank you for using our mail form"; else //if " " is not filled out, display the form echo "<form method='post' action='mailform.php'> <input name=' ' type='text' /><br /> Subject: <input name='subject' type='text' /><br /> Message:<br /> <textarea name='message' rows='15' cols='40'> </textarea><br /> <input type='submit' /> </form>";

120 ARRAY FUNCTION

121 $ar = array(10,20,30,40,50); foreach($ar as $a) echo "<br>the Array Element is:",$a; //Adding Values to the End of an Array > echo "<br>"; $ar[] = 60; foreach($ar as $a) echo "<br>the Array Element is:",$a; //Getting the Size of an Array echo "<br>"; $size = count($ar); echo "<br>the Size of the Array is:",$size;

122 //Padding an Array echo "<br>"; $scores = array(5,10); $padded = array_pad($scores,5,0); foreach($padded as $a3) echo "<br>the Padding of an Array is:",$a3; //Slicing an Array echo "<br>"; $people = array('tom','dick','harriet','brenda','jo'); $middle = array_slice($people,2,2); foreach($middle as $m) echo "<br>the Slicing of an Array is:",$m;

123 //Calculating the Sum of an Array echo "<br>"; $scores = array(98,76,56,80,100); $total = array_sum($scores); echo "<br>the Sum of the Array Element is: ",$total; //Merging of Two Arrays echo "<br>"; $first = array('hello','world'); $second = array('exit','here'); $merged = array_merge($first,$second); foreach($merged as $m) echo "<br>the Array Element is after the Merging ",$m; //Calculating the Difference Between Two Arrays echo "<br>"; $a1 = array('bill','claire','elle','simon','judy'); $a2 = array('jack','claire','toni'); $a3 = array('elle','simon','garfunke1'); $diff = array_diff($a1,$a2,$a3); foreach($diff as $d) echo "<br>the Difference of the all Three Array is: ",$d;

124 //Filtering Elements from an Array echo "<br>"; function is_odd($element) return $element % 2; $numbers = array(9,23,24,27); $odds = array_filter($numbers, 'is_odd'); foreach($odds as $o) echo "<br>the Filtering Element of Odd Numbers is: ",$o; //array_keys() and array_values() echo "<br>"; $data = array("hero" =>"Holmes","villain"=>"Moriarty"); print_r(array_values($data)); echo "<br>"; print_r(array_keys($data));

125 //array_pop() echo "<br>"; $data = array("donald","jim","tom"); array_pop($data); print_r($data); //array_push() echo "<br>"; $data = array("donald","jim"); array_push($data,"harray"); print_r($data); //array_shift() echo "<br>"; $data = array("donald","jim","tom"); array_shift($data); print_r($data);

126 //array_unshift() echo "<br>"; $data = array("donald", //sort() "Jim","Tom"); array_unshift($data,"sarah"); print_r($data); echo "<br>"; $data = array("g","t","a","s"); sort($data); print_r($data); //array_reverse() echo "<br>"; $data = array("g","t","a","s"); print_r(array_reverse($data)); //array_rand() echo "<br>"; $data = array("white","black","red"); echo "Today color is ",$data[array_rand($data)]; //array_search() echo "<br>"; $data = array("blue"=>"#0000cc", black"=>"#000000", "green"=>"#00ff00"); echo "Found,array_search("#0000cc",$data); //array_unique($data) <?pho echo "<br>"; $data = array(1,1,4,6,6,7,4,3,4); print_r(array_unique($data));

127 PHP FILE HANDLING

128 PHP File Handling: File handling in PHP is very easy and effective. Not only files, we can open urls also using php s file functions. Few important file functions in php are, file(); file_get_contents(); file_put_contents(); fopen(); fclose(); fread(); file_exisits(); delete(); filesize(); fwrite(); is_dir(); is_writable();

129 Basic File Operation 1. Creating a File 2. Opening a File 3. Writing a File 4. Reading a File 5. Closing a File Opening a File The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened: <html> <body> </body> </html> $file=fopen("welcome.txt","r");

130 The file may be opened in one of the following modes: Modes r Description Read only. Starts at the beginning of the file r+ Read/Write. Starts at the beginning of the file w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist a+ Read/Append. Preserves file content by writing to the end of the file x Write only. Creates a new file. Returns FALSE and an error if file already exists x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists Note: If the fopen() function is unable to open the specified file, it returns 0 (false).

131 Example The following example generates a message if the fopen() function is unable to open the specified file: <html> <body> $file=fopen("welcome.txt","r") or exit("unable to open file!"); </body> </html> Closing a File The fclose() function is used to close an open file: $file = fopen("test.txt","r"); //some code to be executed fclose($file); Check End-of-file The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length. Note: You cannot read from files opened in w, a, and x mode! if (feof($file)) echo "End of file";

132 Reading a File Line by Line The fgets() function is used to read a single line from a file. Note: After a call to this function the file pointer has moved to the next line. Example The example below reads a file line by line, until the end of file is reached: $file = fopen("welcome.txt", "r") or exit("unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) echo fgets($file). "<br />"; fclose($file); Reading a File Character by Character The fgetc() function is used to read a single character from a file. Note: After a call to this function the file pointer moves to the next character. Example The example below reads a file character by character, until the end of file is reached:

133 $file=fopen("welcome.txt","r") or exit("unable to open file!"); while (!feof($file)) echo fgetc($file); fclose($file); Write into the File: $myfile = "testfile.txt"; $fh = fopen($myfile, 'w') or die("can't open file"); $stringdata = "Bobby Bopper\n"; fwrite($fh, $stringdata); $stringdata = "Tracy Tanner\n"; fwrite($fh, $stringdata); fclose($fh);

134 PHP - LDAP 134

135 Introduction: LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure. The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organizations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents. To refer to a file in a subdirectory on your hard disk, you might use something like: /usr/local/myapp/docs The forwards slash marks each division in the reference, and the sequence is read from left to right. The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be: cn=john Smith,ou=Accounts,o=My Company,c=US The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as: country = US organization = My Company organizationalunit = Accounts commonname = John Smith 135

136 Using the PHP LDAP calls Before you can use the LDAP calls you will need to know.. The name or address of the directory server you will use The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=my Company,c=US") Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else) The typical sequence of LDAP calls you will make in an application will follow this pattern: 136

137 LDAP in PHP: PHP has shipped with support for LDAP since version 3.x of the language, and today comes with built-in support to connect to LDAP databases, perform queries and process result sets. These capabilities make PHP extremely popular among developers who need to create Web applications that interface with LDAP directories. PHP LDAP Functions: PHP offers various functions for LDAP operations. These functions provide an interface for fast and efficient application development. Establishing connection: int ldap_connect(string[host_name], int[port_number]); The function establishes a connection with the LDAP server with the specified host_name and at the port specified by the port_number. The return type of this function is an integer, which is a positive link identifier on success and 0 (false) on failure. When the port no: is not specified, the default port number is 389. Binding to a Directory: After a connection with the server is established, you need to bind your application to a database or a directory.

138 The function for binding to a directory is: int ldap_bind(int link_identifier, string [bind_rdn], string [bind_pwd]); The above function binds the application to the directory with a Relative Distinguished Name (RDN), bind_rdn and using the password, bind_pwd for the directory. The ldap_bind() function is also used to specify access permissions for an end user. If RDN and password are not specified, PHP tries to establish an anonymous bind. An anonymous bind with the LDAP servers helps in searching and fetching data from database. To add or modify data, the LDAP servers require a password. The return type of the ldap_bind() function is an integer which is non-zero or true on success and zero or false on failure. After establishing a connection with the LDAP server and binding the application to a directory, you can use search and modify functions for this directory. Searching for an Entry: The ldap_read() function is used to read data from a database. int ldap_read( int link_identifier, string base_dn, string filter, array [attributes]); The above function extracts an entry from a directory. The search is based on the filter parameter in the base Distinguished Name(DN), base_dn. For searching all entries in the LDAP database, you should use the value, ObjectClass=*, for the filter parameter.

139 The return type of this function is an integer. It returns the search result identifier on success or false on failure. The array [ attributes] parameter used in the ldap_read() function is a regular PHP string array. It specifies the attributes for each record that needs to be fetched from the search query. The ldap_search() function is used to search through a directory. This function differs from the ldap_read() function and searches in all the subdirectories of the base DN. The syntax for the ldap_search() function is int ldap_search(int link_identifier, string base_dn, string filter, array [attributes]); The parameters for the ldap_search() function are the same as the parameters for the ldap_read() function. The ldap_search() function returns a result set identifier for all the retrieved entries. For example, a simple LDAP database consists of user login name, IP address, and time of connection. The steps to perform a successful search on this database are 1. connect to the LDAP server 2. Bind to the required directory 3. Perform the search

140 /* Declaration of the global variable*/ $server_name = localhost ; $port = 389 ; $base_dn = mn=june, yr=2005, ws=osix.net ; $attribs = array( IP, TM ); /* Connect, bind, and search directory */ $link_id = ldap_connect($server_name, $port); If($link_id) echo Connection Successful ; if(ldap_bind($link_id)) //anonymous bind echo Bind successful ; $res = ldap_search($link_id, $base_dn, IP=212*, $attribs); if($res) echo Search successful ; else echo Search Failed ;

141 else echo Bind Failed ; else echo Connection Failed ; In the above code, first a connection is established with the LDAP server at local host port number 389. Then, it performs a bind operation for the directory. An anonymous bind is performed because the search is for records or entries whose IP address begins with 212. LDAP clients that perform anonymous binds are provided read-only access to the data. If the bind is successful, a search is performed on the directory with base DN as mn=june, yr=2005, ws=osix.net and with IP and TM (time of connection). The following function retrieves all the entries in the returned result set, if the search is successful. array ldap_get_entries(int link_identifier, int result_identifier); The above function returns the entries of the result set as a multidimensional array.

142 In addition to the ldap_get_entries() function, PHP LDAP API offers functions, such as ldap_first_entry() and ldap_next_entry(), for fetching search results. To retrieve the first entry from the result set, use the ldap_first_entry() function. int ldap_first_entry(int link_identifier, int result_identifier); The above function returns the result entry identifier corresponding to the first entry in the search result. If the search fails, it returns a false value. To retrieve subsequent entries, use the ldap_next_entry() function. int ldap_next_entry(int link_identifier, int result_entry_identifier); The above function returns the result entry identifier that corresponds to the next entry in the result set. Pass the previously found result entry identifier as a second parameter to this function. This function returns a false value in case there are no more results and also if it fails in retrieving the value. This function is usually run in a while loop until it reaches the end of the result set. You can fetch all the attributes values by using the ldap_get_attributes() function. array ldap_get_attributes(intlink_identifier, int result_entry_identifier); This function returns an array containing all the attributes and their values.

143 Adding/Modifying/Deleting Data: You can add, modify, and delete entries from an LDAP server. You can add, modify, and delete attributes and their values to modify an existing entry. In a typical LDAP server setup, the number of add/delete/modify transaction is limited as compared to the search and display of information. The function for adding attributes and their values to an existing entry is, int ldap_mod_add( int link_identifier, string dn, array entry); This function takes the DN of an existing entry in the second parameter and the attributes and their values as an array in the third parameter. The syntax for the function to delete attributes and their values is, int ldap_mod_del(int link_identifier, string dn, array entry); This function deletes attributes from an existing entry and takes the DN of the entry in the second parameter. It returns true on success and false on failure. The attributes and their values are passed as an array in the third parameter of the function. The syntax for the function to modify the value of an attribute is, int ldap_mod_replace(int link_identifier, string dn, array entry);

144 You can also add new entries to an existing directory if the new entries adhere to the structure of the directory. Every entry has its own unique DN. As a result, when you add a new entry to the directory, its DN has to be passed as a parameter to the ldap_add() function. The syntax for the ldap_add() function is int ldap_add(int link_identifier, string dn, array entry); The return type of the function is an integer that returns true on success and false on failure. The entry array contains the attributes and their values, while dn is the Distinguished Name of the entry. The function for deleting an entry is, int ldap_delete(int link_identifier, string dn); The return type of the function is an integer. It returns true on success and false on failure. This function deletes the entry from the directory specified by the dn, which is passed as second parameter. To change few attributes, you can use the ldap_modify() function. int ldap_modify(int link_identifier, string dn, array entry); The function to close the connection with the LDAP server is, int ldap_close(int link_identifier); This function calls the ldap_unbind() function.

145 PHP STRING FUNCTION

146 addcslashes() Definition and Usage The addcslashes() function returns a string with backslashes in front of the specified characters. Syntax addcslashes(string,characters) Parameter string characters Description Required. Specifies the string to check Required. Specifies the characters or range of characters to be affected by addcslashes() $str = "Hello, my name is Kai Jim."; echo $str."<br />"; echo addcslashes($str,'m')."<br />"; echo addcslashes($str,'k')."<br />"; Output Hello, my name is Kai Jim. Hello, \my na\me is Kai Ji\m. Hello, my name is \Kai Jim.

147 $str = "Hello, my name is Kai Jim."; echo $str."<br />"; echo addcslashes($str,'a..z')."<br />"; echo addcslashes($str,'a..z')."<br />"; echo addcslashes($str,'a..h'); PHP bin2hex() Function Definition and Usage The output of the code above will be: Hello, my name is Kai Jim. \Hello, my name is \Kai \Jim. H\e\l\l\o, \m\y \n\a\m\e \i\s K\a\i J\i\m. H\ello, my n\am\e is K\ai Jim. The bin2hex() function converts a string of ASCII characters to hexadecimal values. The string can be converted back using the pack() function. Parameter string Syntax bin2hex(string) Description Required. The string to be converted

148 $str = "Hello world!"; echo bin2hex($str). "<br />"; echo pack("h*",bin2hex($str)). "<br />"; The output of the code above will be: 48656c6c6f20776f726c6421 Hello world! PHP chr() Function Definition and Usage The chr() function returns a character from the specified ASCII value. Syntax chr(ascii) Parameter ascii Description Required. An ASCII value echo chr(52)."<br />"; echo chr(052)."<br />"; echo chr(0x52)."<br />"; The output of the code above will be: 4 * R

149 PHP chunk_split() Function Definition and Usage The chunk_split() function splits a string into a series of smaller parts. Syntax chunk_split(string,length,end) Parameter string Description Required. Specifies the string to split length Optional. A number that defines the length of the chunks. Default is 76 end Optional. A string that defines what to place at the end of each chunk. Default is \r\n $str = "Hello world!"; echo chunk_split($str,1,"."); $str = "Hello world!"; echo chunk_split($str,6,"..."); The output of the code above will be: H.e.l.l.o..w.o.r.l.d.!. The output of the code above will be: Hello...world!...

150 PHP count_chars() Function Definition and Usage The count_chars() function returns how many times an ASCII character occurs within a string and returns the information. Syntax count_chars(string,mode) Parameter string mode Description Required. The string to be checked Optional. Specifies the return modes. 0 is default. The different return modes are: 0 - an array with the ASCII value as key and number of occurrences as value 1 - an array with the ASCII value as key and number of occurrences as value, only lists occurrences greater than zero 2 - an array with the ASCII value as key and number of occurrences as value, only lists occurrences equal to zero are listed 3 - a string with all the different characters used 4 - a string with all the unused characters

151 $str = "Hello World!"; print_r(count_chars($str,1)); The output of the code above will be: Array ( [32] => 1 [33] => 1 [72] => 1 [87] => 1 [100] => 1 [101] => 1 [108] => 3 [111] => 2 [114] => 1 ) $str = "Hello World!"; echo count_chars($str,3); The output of the code above will be:!hwdelor

152 PHP crc32() Function The crc32() function calculates a 32-bit CRC (cyclic redundancy checksum) for a string. This function can be used to validate data integrity. Syntax Parameter string crc32(string) Description Required. The string to be calculated $str = crc32("hello world!"); echo 'Without %u: '.$str."<br />"; echo 'With %u: '; printf("%u",$str); $str = crc32("hello world."); echo 'Without %u: '.$str."<br />"; echo 'With %u: '; printf("%u",$str); The output of the code above will be: Without %u: With %u: The output of the code above will be: Without %u: With %u:

153 PHP crypt() Function Definition and Usage 1. The crypt() function returns a string encrypted using DES, Blowfish, or MD5 algorithms. 2. This function behaves different on different operating systems, some operating systems supports more than one type of encryption. PHP checks what algorithms are available and what algorithms to use when it is installed. 3. The exact algorithm depends on the format and length of the salt parameter. Salts help make the encryption more secure by increasing the number of encrypted strings that can be generated for one specific string with one specific encryption method. 4. There are some constants that are used together with the crypt() function. The value of these constants are set by PHP when it is installed. Constants: [CRYPT_SALT_LENGTH] - The length of the default encryption. With standard DES encryption, the length is 2 [CRYPT_STD_DES] - Value is 1 if the standard DES algorithm is supported, 0 otherwise. The Standard DES-based encryption has a two character salt

154 [CRYPT_EXT_DES] - Value is1 if the extended DES algorithm is supported, 0 otherwise. The Extended DES encryption has a nine character salt [CRYPT_MD5] - Value is 1 if the MD5 algorithm is supported, 0 otherwise. The MD5 encryption has a 12 character salt starting with $1$ [CRYPT_BLOWFISH] - Value is 1 if the Blowfish algorithm is supported, 0 otherwise. The Blowfish encryption has a 16 character salt starting with $2$ or $2a$ Syntax crypt(str,salt) Parameter str salt Description Required. Specifies the string to be encoded Optional. A string used to increase the number of characters encoded, to make the encoding more secure. If the salt argument is not provided, one will be randomly generated by PHP each time you call this function.

155 if (CRYPT_STD_DES == 1) echo "Standard DES: ".crypt("hello world")."\n<br />"; else echo "Standard DES not supported.\n<br />"; if (CRYPT_EXT_DES == 1) echo "Extended DES: ".crypt("hello world")."\n<br />"; else echo "Extended DES not supported.\n<br />"; if (CRYPT_MD5 == 1) echo "MD5: ".crypt("hello world")."\n<br />";

156 else echo "MD5 not supported.\n<br />"; if (CRYPT_BLOWFISH == 1) echo "Blowfish: ".crypt("hello world"); else echo "Blowfish DES not supported."; The output of the code above could be (depending on the operating system): Standard DES: $1$r35.Y52.$iyiFuvM.zFGsscpU0aZ4e. Extended DES not supported. MD5: $1$BN1.0I2.$8oBI/4mufxK6Tq89M12mk/ Blowfish DES not supported.

157 PHP explode() Function Definition and Usage The explode() function breaks a string into an array. Syntax Parameter separator string limit explode(separator,string,limi t) Description Required. Specifies where to break the string Required. The string to split Optional. Specifies the maximum number of array elements to return $str = "Hello world. It's a beautiful day."; print_r (explode(" ",$str)); Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )

158 PHP fprintf() Function Definition and Usage The fprintf() function writes a formatted string to a specified output stream (example: file or database). The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc. The fprintf() function returns the length of the written string. Syntax fprintf(stream,format,arg1,arg2,arg++) $str = "Hello"; $number = 123; $file = fopen("test.txt","w"); echo fprintf($file,"%s world. Day number %u",$str,$number); The output of the code above will be: 27 The following text will be written to the file "test.txt": Hello world. Day number 123

159 Parameter stream format arg1 arg2 arg++ Description Required. Specifies where to write/output the string Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %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) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value).[0-9] (Specifies the number of decimal digits or maximum string length) Note: If multiple additional format values are used, they must be in the same order as above. Required. The argument to be inserted at the first %-sign in the format string Optional. The argument to be inserted at the second %-sign in the format string Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string

160 PHP implode() Function Definition and Usage The implode() function returns a string from the elements of an array. Syntax implode(separator,array) Parameter Separator Array Description Optional. Specifies what to put between the array elements. Default is "" (an empty string) Required. The array to join to a string $arr = array('hello','world!','beautiful','da y!'); echo implode(" ",$arr); The output of the code above will be: Hello World! Beautiful Day!

161 PHP join() Function Definition and Usage The join() function returns a string from the elements of an array. The join() function is an alias of the implode() function. Syntax join(separator,array) Parameter separator array Description Optional. Specifies what to put between the array elements. Default is "" (an empty string) Required. The array to join to a string $arr = array('hello','world!','beautiful','day!'); echo join(" ",$arr); The output of the code above will be: Hello World! Beautiful Day!

162 PHP localeconv() Function Definition and Usage The localeconv() function returns an array containing local numeric and monetary formatting information. The localeconv() function will return the following array elements: [decimal_point] - Decimal point character [thousands_sep] - Thousands separator [int_curr_symbol] - Currency symbol (example: USD) [currency_symbol] - Currency symbol (example: $) [mon_decimal_point] - Monetary decimal point character [mon_thousands_sep] - Monetary thousands separator [positive_sign] - Positive value character [negative_sign] - Negative value character [int_frac_digits] - International fractional digits [frac_digits] - Local fractional digits [p_cs_precedes] - True (1) if currency symbol is placed in front of a positive value, False (0) if it is placed behind [p_sep_by_space] - True (1) if there is a spaces between the currency symbol and a positive value, False (0) otherwise [n_cs_precedes] - True (1) if currency symbol is placed in front of a negative value, False (0) if it is placed behind

163 [n_sep_by_space] [p_sign_posn] - True (1) if there is a spaces between the currency symbol and a negative value, False (0) otherwise - Formatting options: 0 - Parentheses surround the quantity and currency symbol 1 - The + sign is placed in front of the quantity and currency symbol 2 - The + sign is placed after the quantity and currency symbol 3 - The + sign is placed immediately in front of the currency symbol 4 - The + sign is placed immediately after the currency symbol [n_sign_posn] - Formatting options: 0 - Parentheses surround the quantity and currency symbol 1 - The - sign is placed in front of the quantity and currency symbol 2 - The - sign is placed after the quantity and currency symbol 3 - The - sign is placed immediately in front of the currency symbol 4 - The - sign is placed immediately after the currency symbol [grouping] [mon_grouping] - Array displaying how numbers are grouped (example: 3 indicates ) - Array displaying how monetary numbers are grouped (example: 2 indicates )

164 Syntax localeconv() setlocale(lc_all, 'US'); $locale_info = localeconv(); print_r($locale_info); The output of the code above will be: Array ( [decimal_point] =>. [thousands_sep] =>, [int_curr_symbol] => USD [currency_symbol] => $ [mon_decimal_point] =>. [mon_thousands_sep] =>, [positive_sign] => [negative_sign] => - [int_frac_digits] => 2 [frac_digits] => 2 [p_cs_precedes] => 1 [p_sep_by_space] => 0 [n_cs_precedes] => 1 [n_sep_by_space] => 0 [p_sign_posn] => 3 [n_sign_posn] => 0 [grouping] => Array ([0] => 3) [mon_grouping] => Array ([0] => 3) )

165 PHP ltrim() Function Definition and Usage The ltrim() function will remove whitespaces or other predefined character from the left side of a string. Syntax ltrim(string,charlist) Parameter string charlist Description Required. Specifies the string to check Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed: "\0" - NULL "\t" - tab "\n" - new line "\x0b" - vertical tab "\r" - carriage return " " - ordinary white space

166 <html> <body> $str = " Hello World!"; echo "Without ltrim: ". $str; echo "<br />"; echo "With ltrim: ". ltrim($str); <body> <html> $str = "\r\nhello World!"; echo "Without ltrim: ". $str; echo "<br />"; echo "With ltrim: ". ltrim($str); The browser output of the code above will be: Without ltrim: Hello World! With ltrim: Hello World! The browser output of the code above will be: Without ltrim: Hello World! With ltrim: Hello World!

167 PHP md5() Function Definition and Usage The md5() function calculates the MD5 hash of a string. The md5() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm.From RFC The MD5 Message-Digest Algorithm: "The MD5 messagedigest algorithm takes as input a message of arbitrary length and produces as output a 128- bit "fingerprint" or "message digest" of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be "compressed" in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA." This function returns the calculated MD5 hash on success, or FALSE on failure. Syntax md5(string,raw) Parameter string raw Description Required. The string to be calculated Optional. Specifies hex or binary output format: TRUE - Raw 16 character binary format FALSE - Default. 32 character hex number Note: This parameter was added in PHP 5.0

168 $str = "Hello"; echo md5($str); The output of the code above will be: 8b1a9953c a827abf8c47804d7 $str = "Hello"; echo md5($str); if (md5($str) == '8b1a9953c a827abf8c47804d7') echo "<br />Hello world!"; exit; The output of the code above will be: 8b1a9953c a827abf8c47804d7 Hello world!

169 PHP md5_file() Function Definition and Usage The md5_file() function calculates the MD5 hash of a file. The md5_file() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm. From RFC The MD5 Message-Digest Algorithm: "The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be "compressed" in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA." This function returns the calculated MD5 hash on success, or FALSE on failure. Syntax md5_file(file,raw)

170 Parameter file raw Description Required. The file to be calculated Optional. Specifies hex or binary output format: TRUE - Raw 16 character binary format FALSE - Default. 32 character hex number Note: This parameter was added in PHP 5.0 $filename = "test.txt"; $md5file = md5_file($filename); echo $md5file; $md5file = md5_file("test.txt"); file_put_contents("md5file.txt",$md5file); The output of the code above will be: The file is ok. The output of the code above will be: 5d41402abc4b2a76b9719d911017c592 $md5file = file_get_contents("md5file.txt"); if (md5_file("test.txt") == $md5file) echo "The file is ok."; else echo "The file has been changed.";

171 PHP ord() Function Definition and Usage The ord() function returns the ASCII value of the first character of a string. Syntax ord(string) Parameter string Description Required. The string to get an ASCII value from echo ord("h")."<br />"; echo ord("hello")."<br />"; The output of the code above will be:

172 PHP printf() Function Definition and Usage The printf() function outputs a formatted string. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc. Syntax printf(format,arg1,arg2,arg++) $str = "Hello"; $number = 123; printf("%s world. Day number %u",$str,$number); The output of the code above will be: Hello world. Day number 123

173 Parameter Format arg1 arg2 arg++ Description Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %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) + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value).[0-9] (Specifies the number of decimal digits or maximum string length) Note: If multiple additional format values are used, they must be in the same order as above. Required. The argument to be inserted at the first %-sign in the format string Optional. The argument to be inserted at the second %-sign in the format string Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string

174 $number = 123; printf("%f",$number); The output of the code above will be: $number = 123; printf("with 2 decimals: %1\$.2f <br />With no decimals: %1\$u",$number); The output of the code above will be: With 2 decimals: With no decimals: 123 PHP rtrim() Function Definition and Usage The rtrim() function will remove whitespaces or other predefined character from the right side of a string. Syntax rtrim(string,charlist)

175 Parameter string charlist Description Required. Specifies the string to check Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed: "\0" - NULL "\t" - tab "\n" - new line "\x0b" - vertical tab "\r" - carriage return " " - ordinary white space <html> <body> $str = "Hello World! "; echo "Without rtrim: ". $str; echo "<br />"; echo "With rtrim: ". rtrim($str); <body> <html> The output of the code above will be: Without rtrim: Hello World! With rtrim: Hello World!

176 PHP similar_text() Function Definition and Usage The similar_text() function returns the number of matching characters of two strings. It can also calculate the similarity of the two strings in percent. Syntax similar_text(string1,string2,percent) Parameter string1 string2 percent Description Required. Specifies the first string to be compared Required. Specifies the second string to be compared Optional. Specifies a variable name for storing the similarity in percent echo similar_text("hello World","Hello Peter"); The output of the code above will be: 7

177 similar_text("hello World","Hello Peter",$percent); echo $percent; The output of the code above will be: PHP sprintf() Function Definition and Usage The sprintf() function writes a formatted string to a variable. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc. Syntax sprintf(format,arg1,arg2,arg++)

178 Parameter format arg1 arg2 arg++ Description Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %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) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value).[0-9] (Specifies the number of decimal digits or maximum string length) Note: If multiple additional format values are used, they must be in the same order as above. Required. The argument to be inserted at the first %-sign in the format string Optional. The argument to be inserted at the second %-sign in the format string Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string

179 $str = "Hello"; $number = 123; $txt = sprintf("%s world. Day number %u",$str,$number); echo $txt; The output of the code above will be: Hello world. Day number 123 $number = 123; $txt = sprintf("%f",$number); echo $txt; The output of the code above will be: $number = 123; $txt = sprintf("with 2 decimals: %1\$.2f <br />With no decimals: %1\$u",$number); echo $txt; The output of the code above will be: With 2 decimals: With no decimals: 123

180 PHP sscanf() Function Definition and Usage The sscanf() function parses input from a string according to a specified format. The sscanf() function parses a string into variables based on the format string. If only two parameters are passed to this function, the data will be returned as an array. Otherwise, if optional parameters are passed, the data parsed are stored in them. If there are more specifiers than variables to contain them, an error occurs. However, if there are less specifiers than variables, the extra variables contain NULL. Syntax sscanf(string,format,arg1,arg2,arg++)

181 Parameter string format arg1 arg2 arg++ Description Required. Specifies the string to read Required. Specifies the format to use. Possible format values: %% - Returns a percent sign %b - Binary number %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) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value).[0-9] (Specifies the number of decimal digits or maximum string length) Note: If multiple additional format values are used, they must be in the same order as above. Optional. The first variable to store data in Optional. The second variable to store data in Optional. The third, fourth, and so on, to store data in

182 $string = "age:30 weight:60kg"; sscanf($string,"age:%d weight:%dkg",$age,$weight); // show types and values var_dump($age,$weight); The output of the code above will be: int(30) int(60) PHP str_ireplace() Function Definition and Usage The str_ireplace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array If the string to be searched is an array, find and replace is performed with every array element If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace If find is an array and replace is a string, the replace string will be used for every find value

183 Syntax str_ireplace(find,replace,string,count) Parameter find replace string count Description Required. Specifies the value to find Required. Specifies the value to replace the value in find Required. Specifies the string to be searched Optional. A variable that counts the number of replacements The output of the code above will be: echo str_ireplace("world","peter","hello world!"); Hello Peter! $arr = array("blue","red","green","yellow"); print_r(str_ireplace("red","pink",$arr,$i)); echo "Replacements: $i"; The output of the code above will be: Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) Replacements: 1

184 $find = array("hello","world"); $replace = array("b"); $arr = array("hello","world","!"); print_r(str_ireplace($find,$replace,$arr)); The output of the code above will be: Array ( [0] => B [1] => [2] =>! ) PHP str_pad() Function Definition and Usage The str_pad() function pads a string to a new length. Syntax str_pad(string,length,pad_string,pad_type) $str = "Hello World"; echo str_pad($str,20,"."); The output of the code above will be: Hello World...

185 Parameter string length pad_string pad_type Description Required. Specifies the string to pad Required. Specifies the new string length. If this value is less than the original length of the string, nothing will be done Optional. Specifies the string to use for padding. Default is whitespace Optional. Specifies what side to pad the string. Possible values: STR_PAD_BOTH - Pad to both sides of the string. If not an even number, the right side gets the extra padding STR_PAD_LEFT - Pad to the left side of the string STR_PAD_RIGHT - Pad to the right side of the string. This is default $str = "Hello World"; echo str_pad($str,20,".",str_pad_left); The output of the code above will be:...hello World $str = "Hello World"; echo str_pad($str,20,".:",str_pad_both); The output of the code above will be:.:.:hello World.:.:.

186 PHP str_repeat() Function Definition and Usage The str_repeat() function repeats a string a specified number of times. Parameter string repeat Syntax Description str_repeat(string,repeat) Required. Specifies the string to repeat Required. Specifies the number of times the string will be repeated. Must be greater or equal to 0 echo str_repeat(".",13); The output of the code above will be:...

187 PHP str_replace() Function Definition and Usage The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array If the string to be searched is an array, find and replace is performed with every array element If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace If find is an array and replace is a string, the replace string will be used for every find value Syntax str_replace(find,replace,string,count)

188 Parameter find replace string count Description Required. Specifies the value to find Required. Specifies the value to replace the value in find Required. Specifies the string to be searched Optional. A variable that counts the number of replacements The output of the code above will be: echo str_replace("world","peter","hello world!"); Hello Peter! $arr = array("blue","red","green","yellow"); print_r(str_replace("red","pink",$arr,$i)); echo "Replacements: $i"; $find = array("hello","world"); $replace = array("b"); $arr = array("hello","world","!"); print_r(str_replace($find,$replace,$arr)); The output of the code above will be: Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) Replacements: 1 The output of the code above will be: array ( [0] => B [1] => [2] =>! )

189 PHP str_shuffle() Function Definition and Usage The str_shuffle() function randomly shuffles all the characters of a string. Syntax str_shuffle(string) Parameter string Description Required. Specifies the string to shuffle echo str_shuffle("hello World"); The output of the code above could be: H leoowlrld PHP wordwrap() Function Definition and Usage The wordwrap() function wraps a string into new lines when it reaches a specific length. This function returns the string broken into lines on success, or FALSE on failure.

190 Syntax Parameter string wordwrap(string,width,break,cut) Description Required. Specifies the string to break up into lines width Optional. Specifies the maximum line width. Default is 75 break cut Optional. Specifies the characters to use as break. Default is "\n" Optional. Specifies whether words longer than the specified width should be wrapped. Default is FALSE (no-wrap) $str = "An example on a long word is: Supercalifragulistic"; echo wordwrap($str,15); The browser output of the code above will be: An example on a long word is: Supercalifragulistic If you select "View source" in the browser window, you will see the following HTML: <html> <body> An example on a long word is: Supercalifragulistic </body> </html>

191 $str = "An example on a long word is: Supercalifragulistic"; echo wordwrap($str,15,"<br />\n"); The output of the code above will be: An example on a long word is: Supercalifragulistic $str = "An example on a long word is: Supercalifragulistic"; echo wordwrap($str,15,"<br />\n",true); The output of the code above will be: An example on a long word is: Supercalifragul istic

192 PHP vsprintf() Function Definition and Usage The vsprintf() function writes a formatted string to a variable. Unlike sprintf(), the arguments in vsprintf(), are placed in an array. The array elements will be inserted at the percent (%) signs in the main string. This function works "step-by-step". At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, etc. Syntax vsprintf(format,argarray) $str = "Hello"; $number = 123; $txt = vsprintf("%s world. Day number %u",array($str,$number)); echo $txt; The output of the code above will be: Hello world. Day number 123

193 Parameter format Description Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %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) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value).[0-9] (Specifies the number of decimal digits or maximum string length) Note: If multiple additional format values are used, they must be in the same order as above. argarray Required. An array with arguments to be inserted at the % signs in the format string

194 $num1 = 123; $num2 = 456; $txt = vsprintf("%f%f",array($num1,$num2)); echo $txt; The output of the code above will be: $number = 123; $txt = vsprintf("with 2 decimals: %1\$.2f <br />With no decimals: %1\$u",array($number)); echo $txt; PHP vprintf() Function Definition and Usage The vprintf() function outputs a formatted string. The output of the code above will be: With 2 decimals: With no decimals: 123 Unlike printf(), the arguments in vprintf(), are placed in an array. The array elements will be inserted at the percent (%) signs in the main string. This function works "step-by-step". At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, etc.

195 Syntax Parameter format vprintf(format,argarray) Description Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %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) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value).[0-9] (Specifies the number of decimal digits or maximum string length) Note: If multiple additional format values are used, they must be in the same order as above. argarray Required. An array with arguments to be inserted at the % signs in the format string

196 $str = "Hello"; $number = 123; vprintf("%s world. Day number %u",array($str,$number)); The output of the code above will be: Hello world. Day number 123 $num1 = 123; $num2 = 456; vprintf("%f%f",array($num1,$num2)); The output of the code above will be: $number = 123; vprintf("with 2 decimals: %1\$.2f <br />With no decimals: %1\$u",array($number)); The output of the code above will be: With 2 decimals: With no decimals: 123

197 PHP vfprintf() Function Definition and Usage The vfprintf() function writes a formatted string to a specified output stream (example: file or database). Unlike fprintf(), the arguments in vfprintf(), are placed in an array. The array elements will be inserted at the percent (%) signs in the main string. This function works "step-by-step". At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, etc. The vfprintf() function returns the length of the written string. Syntax vfprintf(stream,format,argarray) $str = "Hello"; $number = 123; $file = fopen("test.txt","w"); echo vfprintf($file,"%s world. Day number %u",array($str,$number)); The output of the code above will be: The following text will be written to the file "test.txt": 27 Hello world. Day number 123

198 The following text will be written to the file "test.txt": $num1 = 123; $num2 = 456; $file = fopen("test.txt","w"); vfprintf($file,"%f%f",array($num1,$num2)); $number = 123; $file = fopen("test.txt","w"); vfprintf($file,"with 2 decimals: %1\$.2f \nwith no decimals: %1\$u",array($number)); The following text will be written to the file "test.txt": With 2 decimals: With no decimals: 123

199 PHP ucwords() Function Definition and Usage The ucwords() function converts the first character of each word in a string to uppercase. Syntax ucwords(string) Parameter string Description Required. Specifies the string to convert echo ucwords("hello world"); The output of the code above will be: Hello World PHP ucfirst() Function Definition and Usage The ucfirst() function converts the first character of a string to uppercase.

200 Syntax ucfirst(string) Parameter string Description Required. Specifies the string to convert echo ucfirst("hello world"); PHP trim() Function Definition and Usage The output of the code above will be: Hello world The trim() function removes whitespaces and other predefined characters from both sides of a string. Syntax trim(string,charlist)

201 Parameter string charlist Description Required. Specifies the string to check Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed: "\0" - NULL "\t" - tab "\n" - new line "\x0b" - vertical tab "\r" - carriage return " " - ordinary white space <html> <body> $str = " Hello World! "; echo "Without trim: ". $str; echo "<br />"; echo "With trim: ". trim($str); <body> <html> The browser output of the code above will be: Without trim: Hello World! With trim: Hello World! If you select "View source" in the browser window, you will see the following HTML: <html> <body> Without trim: Hello World! <br />With trim: Hello World! </body> </html>

202 $str = "\r\nhello World!\r\n"; echo "Without trim: ". $str; echo "<br />"; echo "With trim: ". trim($str); The browser output of the code above will be: Without trim: Hello World! With trim: Hello World! If you select "View source" in the browser window, you will see the following HTML: PHP substr_replace() Function <html> <body> Without trim: Hello World! <br />With trim: Hello World! </body> </html> Definition and Usage The substr_replace() function replaces a part of a string with another string. Syntax substr_replace(string,replacement,start,length)

203 Parameter string replacement start length Description Required. Specifies the string to check Required. Specifies the string to insert Required. Specifies where to start replacing in the string A positive number - Start replacing at the specified position in the string Negative number - Start replacing at the specified position from the end of the string 0 - Start replacing at the first character in the string Optional. Specifies how many characters should be replaced. Default is the same length as the string. A positive number - The length of string to be replaced A negative number - How many characters should be left at end of string after replacing 0 - Insert instead of replace echo substr_replace("hello world","earth",6); The output of the code above will be: Hello earth

204 PHP substr_count() Function Definition and Usage The substr_count() function counts the number of times a substring occurs in a string. Syntax substr_count(string,substring,start,length) Parameter string substring start length Description Required. Specifies the string to check Required. Specifies the string to search for Optional. Specifies where in string to start searching Optional. Specifies the length of the search echo substr_count("hello world. The world is nice","world"); The output of the code above will be: 2

205 PHP substr_compare() Function Definition and Usage The substr_compare() function compares two strings from a specified start position. This function returns: 0 - if the two strings are equal <0 - if string1 (from startpos) is less than string2 >0 - if string1 (from startpos) is greater than string2 If length is equal or greater than length of string1, this function returns FALSE. Syntax substr_compare(string1,string2,startpos,length,case)

206 Parameter Description string1 string2 startpos length case Required. Specifies the first string to compare Required. Specifies the second string to compare Required. Specifies where to start comparing in string1 Optional. Specifies how much of string1 to compare Optional. Specifies whether or not to perform a case-sensitive compare. Default is FALSE (case-sensitive) echo substr_compare("hello world","hello world",0); The output of the code above will be: echo substr_compare("hello world","world",6); The output of the code above will be: echo substr_compare("hello world","world",6,true); The output of the code above will be: 0 0 0

207 PHP substr() Function Definition and Usage The substr() function returns a part of a string. Syntax substr(string,start,length) Parameter Description string start length Required. Specifies the string to return a part of Required. Specifies where to start in the string A positive number - Start at a specified position in the string A negative number - Start at a specified position from the end of the string 0 - Start at the first character in string Optional. Specifies the length of the returned string. Default is to the end of the string. A positive number - The length to be returned from the start parameter Negative number - The length to be returned from the end of the string

208 echo substr("hello world!",6); echo substr("hello world!",6,5); PHP strtr() Function Definition and Usage The output of the code above will be: world! The output of the code above will be: world The strtr() function translates certain characters in a string. Syntax strtr(string,from,to) OR strtr(string,array) Parameter string from to array Description Required. Specifies the string to translate Required (unless array is used). Specifies what characters to change Required (unless array is used). Specifies what characters to change into Required (unless to and from is used). An array containing what to change from as key, and what to change to as value

209 PHP strtolower() Function Definition and Usage The strtolower() function converts a string to lowercase. Syntax strtolower(string) Parameter string Description Required. Specifies the string to convert echo strtolower("hello WORLD!"); The output of the code above will be: hello world

210 echo strtr("hilla Warld","ia","eo"); $arr = array("hello" => "Hi", "world" => "earth"); echo strtr("hello world",$arr); PHP strtoupper() Function Definition and Usage The output of the code above will be: Hello World The output of the code above will be: Hi earth The strtoupper() function converts a string to uppercase. Syntax strtoupper(string) Parameter string Description Required. Specifies the string to convert echo strtoupper("hello WORLD!"); The output of the code above will be: HELLO WORLD!

211 PHP strtok() Function Definition and Usage The strtok() function splits a string into smaller strings. Syntax strtok(string,split) Parameter string split Description Required. Specifies the string to split Required. Specifies one or more split characters $string = "Hello world. Beautiful day today."; $token = strtok($string, " "); while ($token!= false) echo "$token<br />"; $token = strtok(" "); The output of the code above will be: Hello world. Beautiful day today.

212 PHP strstr() Function Definition and Usage The strstr() function searches for the first occurrence of a string inside another string. This function returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found. Syntax Parameter string search strstr(string,search) Description Required. Specifies the string to search Required. Specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number echo strstr("hello world!","world"); The output of the code above will be: world!

213 echo strstr("hello world!",111); The output of the code above will be: o world! PHP strspn() Function Definition and Usage The strspn() function returns the number of characters found in the string that contains only characters from the charlist. Syntax Parameter string charlist start length strspn(string,charlist,start,length) Description Required. Specifies the string to search Required. Specifies the characters to find Optional. Specifies where in the string to start Optional. Defines the length of the string echo strspn("hello world!","khlleo"); The output of the code above will be: 5

214 echo strspn("abcdefand","abc"); The output of the code above will be: 3 PHP strrpos() Function Definition and Usage The strrpos() function finds the position of the last occurrence of a string inside another string. This function returns the position on success, otherwise it returns FALSE. Parameter string find start Syntax strrpos(string,find,start) Description Required. Specifies the string to search Required. Specifies the string to find Optional. Specifies where to begin the search echo strrpos("hello world!","wo"); The output of the code above will be: 6

215 PHP strripos() Function Definition and Usage The strripos() function finds the position of the last occurrence of a string inside another string. This function returns the position on success, otherwise it returns FALSE. Syntax Parameter string find start strripos(string,find,start) Description Required. Specifies the string to search Required. Specifies the string to find Optional. Specifies where to begin the search echo strripos("hello world!","wo"); The output of the code above will be: 6

216 PHP strrev() Function Definition and Usage The strrev() function reverses a string. Syntax strrev(string) Parameter Description string Required. Specifies the string to reverse echo strrev("hello World!"); PHP strrchr() Function Definition and Usage The output of the code above will be:!dlrow olleh The strrchr() function finds the position of the last occurrence of a string within another string, and returns all characters from this position to the end of the string. If char cannot be found, this function returns FALSE.

217 Syntax strrchr(string,char) Parameter string char Description Required. Specifies the string to search Required. Specifies the string to find. If this is a number, it will search for the character matching the ASCII value of that number echo strrchr("hello world!","world"); echo strrchr("hello world!",111); PHP strpos() Function Definition and Usage The output of the code above will be: world! The output of the code above will be: orld! The strpos() function returns the position of the first occurrence of a string inside another string. If the string is not found, this function returns FALSE.

218 Syntax strpos(string,find,start) Parameter string find start Description Required. Specifies the string to search Required. Specifies the string to find Optional. Specifies where to begin the search echo strpos("hello world!","wo"); The output of the code above will be: 6

219 PHP FILE SYSTEMS

220 PHP basename() Function Definition and Usage The basename() function returns the filename from a path. Syntax basename(path,suffix) Parameter path suffix Description Required. Specifies the path to check Optional. Specifies a file extension. If the filename has this file extension, the file extension will not show $path = "/testweb/home.php"; //Show filename with file extension echo basename($path)."<br/>"; The output of the code above will be: home.php home //Show filename without file extension echo basename($path,".php");

221 PHP copy() Function Definition and Usage The copy() function copies a file. This function returns TRUE on success and FALSE on failure. Syntax copy(file,to_file) Parameter Description file Required. Specifies the file to copy to_file Required. Specifies the file to copy to echo copy("source.txt","target.txt"); PHP dirname() Function Definition and Usage The output of the code above will be: 1 The dirname() function returns the directory name from a path.

222 Syntax dirname(path) Parameter Description path Required. Specifies the path to check echo dirname("c:/testweb/home.php"). "<br />"; echo dirname("/testweb/home.php"); PHP disk_free_space() Function Definition and Usage The output of the code above will be: c:/testweb /testweb The disk_free_space() function returns the free space, in bytes, of the specified directory. Syntax disk_free_space(directory) Parameter Description directory Required. Specifies the directory to check

223 echo disk_free_space("c:"); The output of the code above could be: PHP disk_total_space() Function Definition and Usage The disk_total_space() function returns the total space, in bytes, of the specified directory. Syntax disk_total_space(directory) Parameter Description directory Required. Specifies the directory to check echo disk_total_space("c:"); The output of the code above could be:

224 PHP fgetss() Function Definition and Usage The fgetss() function returns a line, with HTML and PHP tags removed, from an open file. The fgetss() function stops returning on a new line, at the specified length, or at EOF, whichever comes first. This function returns FALSE on failure. Syntax fgetss(file,length,tags) Parameter Description file length tags Required. Specifies the file to check Optional. Specifies the number of bytes to read. Default is 1024 bytes. Note: This parameter is required in versions prior to PHP 5 Optional. Specifies tags that will not be removed

225 $file = fopen("test.htm","r"); echo fgetss($file); fclose($file); $file = fopen("test.htm","r"); echo fgetss($file,1024,"<p>,<b>"); fclose($file); PHP file() Function Definition and Usage The output of the code above will be: This is a paragraph. The output of the code above will be: This is a paragraph. The file() reads a file into an array. Each array element contains a line from the file, with newline still attached. Syntax file(path,include_path,context)

226 Parameter path include_path context Description Required. Specifies the file to read Optional. Set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream. Can be skipped by using NULL. print_r(file("test.txt")); PHP fileatime() Function Definition and Usage The output of the code above will be: Array ( [0] => Hello World. Testing testing! [1] => Another day, another line. [2] => If the array picks up this line, [3] => then is it a pickup line? ) The fileatime() function returns the last access time of the specified file. This function returns the last access time as a Unix timestamp on success, FALSE on failure.

227 Syntax fileatime(filename) Parameter Description filename Required. Specifies the file to check echo fileatime("test.txt"); echo "<br />"; echo "Last access: ".date("f d Y H:i:s.",fileatime("test.txt")); The output of the code above could be: Last access: February :48:21. PHP filectime() Function Definition and Usage The filectime() function returns the last time the specified file was changed. This function checks for the inode changes as well as regular changes. Inode changes is when permissions, owner, group or other metadata is changed. This function returns the last change time as a Unix timestamp on success, FALSE on failure.

228 Syntax filectime(filename) Parameter Description filename Required. Specifies the file to check echo filectime("test.txt"); echo "<br />"; echo "Last change: ".date("f d Y H:i:s.",filectime("test.txt")); The output of the code above could be: PHP filemtime() Function Definition and Usage Last change: January :26:32. The filemtime() function returns the last time the file content was modified. This function returns the last change time as a Unix timestamp on success, FALSE on failure.

229 Syntax filemtime(filename) Parameter Description filename Required. Specifies the file to check echo filemtime("test.txt"); echo "<br />"; echo "Last modified: ".date("f d Y H:i:s.",filemtime("test.txt")); The output of the code above could be: Last modified: February :22:46.

230 PHP filesize() Function Definition and Usage The filesize() function returns the size of the specified file. This function returns the file size in bytes on success or FALSE on failure. Syntax filesize(filename) Parameter Description filename Required. Specifies the file to check echo filesize("test.txt"); The output of the code above will be: 20

231 PHP filetype() Function Definition and Usage The filetype() function returns the file type of a specified file or directory. This function returns the one of seven possible values on success or FALSE on failure. Possible return values: fifo char dir block link file unknown Syntax Parameter filename filetype(filename) Description Required. Specifies the file to check echo filetype("test.txt"); echo filetype("images"); The output of the code above will be: file The output of the code above will be: dir

232 PHP flock() Function Definition and Usage The flock() function locks or releases a file. This function returns TRUE on success or FALSE on failure. Syntax flock(file,lock,block) Parameter file lock block Description Required. Specifies an open file to lock or release Required. Specifies what kind of lock to use. Possible values: LOCK_SH - Shared lock (reader). Allow other processes to access the file LOCK_EX - Exclusive lock (writer). Prevent other processes from accessing the file LOCK_UN - Release a shared or exclusive lock LOCK_NB - Avoids blocking other processes while locking Optional. Set to 1 to block other processes while locking

233 $file = fopen("test.txt","w+"); // exclusive lock if (flock($file,lock_ex)) fwrite($file,"write something"); // release lock flock($file,lock_un); else echo "Error locking file!"; fclose($file);

234 PHP fread() Function Definition and Usage The fread() reads from an open file. The function will stop at the end of the file or when it reaches the specified length, whichever comes first. This function returns the read string, or FALSE on failure. Syntax fread(file,length) Parameter file length Description Read 10 bytes from file: $file = fopen("test.txt","r"); fread($file,"10"); fclose($file); Required. Specifies the open file to read from Required. Specifies the maximum number of bytes to read Read entire file: $file = fopen("test.txt","r"); fread($file,filesize("test.txt")); fclose($file);

235 PHP fseek() Function Definition and Usage The fseek() function seeks in an open file. This function moves the file pointer from its current position to a new position, forward or backward, specified by the number of bytes. This function returns 0 on success, or -1 on failure. Seeking past EOF will not generate an error. Syntax fseek(file,offset,whence) Parameter file offset whence Description Required. Specifies the open file to seek in Required. Specifies the new position (measured in bytes from the beginning of the file) Optional. (added in PHP 4). Possible values: SEEK_SET - Set position equal to offset. Default SEEK_CUR - Set position to current location plus offset SEEK_END - Set position to EOF plus offset (to move to a position before EOF, the offset must be a negative value)

236 $file = fopen("test.txt","r"); // read first line fgets($file); // move back to beginning of file fseek($file,0); PHP fstat() Function Definition and Usage The fstat() function returns information about an open file. This function returns an array with the following elements: [0] or [dev] - Device number [1] or [ino] - Inode number [2] or [mode] - Inode protection mode [3] or [nlink] - Number of links [4] or [uid] - User ID of owner [5] or [gid] - Group ID of owner [6] or [rdev] - Inode device type [7] or [size] - Size in bytes [8] or [atime] - Last access (as Unix timestamp) [9] or [mtime] - Last modified (as Unix timestamp) [10] or [ctime] - Last inode change (as Unix timestamp) [11] or [blksize] - Blocksize of filesystem IO (if supported) [12] or [blocks] - Number of blocks allocated

237 Syntax fstat(file) Parameter Description file $file = fopen("test.txt","r"); print_r(fstat($file)); fclose($file); Required. Specifies the open file to check Array ( [0] => 0 [1] => 0 [2] => [3] => 1 [4] => 0 [5] => 0 [6] => 0 [7] => 92 [8] => [9] => [10] => [11] => -1 [12] => -1 The output of the code above could be: [dev] => 0 [ino] => 0 [mode] => [nlink] => 1 [uid] => 0 [gid] => 0 [rdev] => 0 [size] => 92 [atime] => [mtime] => [ctime] => [blksize] => -1 [blocks] => -1 )

238 PHP ftell() Function Definition and Usage The ftell() function returns the current position in an open file. Returns the current file pointer position, or FALSE on failure. Parameter file Syntax ftell(file) Description Required. Specifies the open file to check $file = fopen("test.txt","r"); // print current position echo ftell($file); The output of the code above will be: 0 15 // change current position fseek($file,"15"); // print current position again echo "<br />". ftell($file); fclose($file);

239 PHP ftruncate() Function Definition and Usage The ftruncate() function truncates an open file to the specified length. Returns TRUE on success, or FALSE on failure. Syntax ftruncate(file,size) Parameter Description file size Required. Specifies the open file to truncate Required. Specifies the new file size //check filesize echo filesize("test.txt"); echo "<br />"; $file = fopen("test.txt", "a+"); ftruncate($file,100); fclose($file); The output of the code above will be: //Clear cache and check filesize again clearstatcache(); echo filesize("test.txt");

240 PHP is_dir() Function Definition and Usage The is_dir() function checks whether the specified file is a directory. This function returns TRUE if the directory exists. Syntax is_dir(file) Parameter Description file $file = "images"; if(is_dir($file)) echo ("$file is a directory"); else echo ("$file is not a directory"); Required. Specifies the file to check The output of the code above could be: images is a directory

241 PHP is_executable() Function Definition and Usage The is_executable() function checks whether the specified file is executable. This function returns TRUE if the file is executable. Syntax is_executable(file) Parameter Description file $file = "setup.exe"; if(is_executable($file)) echo ("$file is executable"); else echo ("$file is not executable"); Required. Specifies the file to check The output of the code above could be: setup.exe is executable

242 PHP is_file() Function Definition and Usage The is_file() function checks whether the specified file is a regular file. This function returns TRUE if it is a file. Syntax is_file(file) Parameter Description file Required. Specifies the file to check $file = "test.txt"; if(is_file($file)) echo ("$file is a regular file"); else echo ("$file is not a regular file"); The output of the code above could be: test.txt is a regular file

243 PHP is_link() Function Definition and Usage The is_link() function checks whether the specified file is a link. This function returns TRUE if it is a link. Syntax is_link(file) Parameter Description file Required. Specifies the file to check $link = "images"; if(is_link($link)) echo ("$link is a link"); else echo ("$link is not a link"); The output of the code above could be: images is not a link

244 PHP lstat() Function Definition and Usage The lstat() function returns information about a file or symbolic link. This function returns an array with the following elements: [0] or [dev] - Device number [1] or [ino] - Inode number [2] or [mode] - Inode protection mode [3] or [nlink] - Number of links [4] or [uid] - User ID of owner [5] or [gid] - Group ID of owner [6] or [rdev] - Inode device type [7] or [size] - Size in bytes [8] or [atime] - Last access (as Unix timestamp) [9] or [mtime] - Last modified (as Unix timestamp) [10] or [ctime] - Last inode change (as Unix timestamp) [11] or [blksize] - Blocksize of filesystem IO (if supported) [12] or [blocks] - Number of blocks allocated

245 Syntax lstat(file) Parameter Description file print_r(lstat("test.txt")); The output of the code above could be: Array ( [0] => 0 [1] => 0 [2] => [3] => 1 [4] => 0 [5] => 0 [6] => 0 [7] => 92 [8] => [9] => [10] => [11] => -1 [12] => -1 Required. Specifies the file to check [dev] => 0 [ino] => 0 [mode] => [nlink] => 1 [uid] => 0 [gid] => 0 [rdev] => 0 [size] => 92 [atime] => [mtime] => [ctime] => [blksize] => -1 [blocks] => -1 )

246 PHP mkdir() Function Definition and Usage Parameter path mode The mkdir() function creates a directory. This function returns TRUE on success, or FALSE on failure. Syntax Description mkdir(path,mode,recursive,context) Required. Specifies the name of the directory to create Optional. Specifies permissions. By default, the mode is 0777 (widest possible access). The mode parameter consists of four numbers: The first number is always zero The second number specifies permissions for the owner The third number specifies permissions for the owner's user group The fourth number specifies permissions for everybody else Possible values (to set multiple permissions, add up the following numbers): 1 = execute permissions 2 = write permissions 4 = read permissions recursive Optional. Specifies if the recursive mode is set (added in PHP 5) context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream (added in PHP 5)

247 PHP REGULAR EXPRESSION 247

248 Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality. Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks. PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain type of regular expression. You can use any of them based on your comfort. POSIX Regular Expressions PERL Style Regular Expressions POSIX Regular Expressions: The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression: various elements (operators) are combined to form more complex expressions. The simplest regular expression is one that matches a single character, such as g, inside strings such as g, haggle, or bag. Lets give explaination for few concepts being used in POSIX regular expression. After that we will introduce you wih regular expression related functions. Brackets Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters. 248

249 The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v. Quantifiers: The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each pecial character having a specific connotation. The +, *,?, int. range, and $ flags all follow a character sequence. 249

250 Examples: Following examples will clear your concepts about matching chracters. Predefined Character Ranges For your programming convenience several predefined character ranges, also known as character classes, are available. Character classes specify an entire range of characters, for example, the alphabet or an integer set: 250

251 PERL Style Regular Expressions: Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the quantifiers introduced in the previous POSIX section. Lets give explaination for few concepts being used in PERL regular expressions. After that we will introduce you wih regular expression related functions. Metacharacters A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning. For instance, you can search for large money sums using the '\d' metacharacter: /([\d]+)000/, Here \d will search for any string of numerical character. Following is the list of metacharacters which can be used in PERL Style Regular Expressions. 251

252 Modifiers Several modifiers are available that can make your work with regexps much easier, like case sensitivity, searching in multiple lines etc. PHP's Regexp PERL Compatible Functions PHP offers following functions for searching strings using Perl-compatible regular expressions: 252

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel Introduction: PHP (Hypertext Preprocessor) was invented by Rasmus Lerdorf in 1994. First it was known as Personal Home Page. Later

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

What is PHP? [1] Figure 1 [1]

What is PHP? [1] Figure 1 [1] PHP What is PHP? [1] PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open source scripting language PHP scripts are executed on the server PHP is free to download and use Figure

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users Introduction to PHP Let's Look Back We talked about how to create a form in HTML Forms are one way to interact with users Users can enter information into forms which can be used by you (programmer) We

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Programming for the Web with PHP

Programming for the Web with PHP Aptech Ltd Version 1.0 Page 1 of 11 Table of Contents Aptech Ltd Version 1.0 Page 2 of 11 Abstraction Anonymous Class Apache Arithmetic Operators Array Array Identifier arsort Function Assignment Operators

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

CGS 3066: Spring 2015 JavaScript Reference

CGS 3066: Spring 2015 JavaScript Reference CGS 3066: Spring 2015 JavaScript Reference Can also be used as a study guide. Only covers topics discussed in class. 1 Introduction JavaScript is a scripting language produced by Netscape for use within

More information

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37) PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37) A Server-side Scripting Programming Language An Introduction What is PHP? PHP stands for PHP: Hypertext Preprocessor. It is a server-side

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

CERTIFICATE IN WEB PROGRAMMING

CERTIFICATE IN WEB PROGRAMMING COURSE DURATION: 6 MONTHS CONTENTS : CERTIFICATE IN WEB PROGRAMMING 1. PROGRAMMING IN C and C++ Language 2. HTML/CSS and JavaScript 3. PHP and MySQL 4. Project on Development of Web Application 1. PROGRAMMING

More information

PHP. Interactive Web Systems

PHP. Interactive Web Systems PHP Interactive Web Systems PHP PHP is an open-source server side scripting language. PHP stands for PHP: Hypertext Preprocessor One of the most popular server side languages Second most popular on GitHub

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction

More information

Chapter 7:- PHP. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

Chapter 7:- PHP. Compiled By:- Sanjay Patel Assistant Professor, SVBIT. Chapter 7:- PHP Compiled By:- Assistant Professor, SVBIT. Outline Starting to script on server side, Arrays, Function and forms, Advance PHP Databases:-Basic command with PHP examples, Connection to server,

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley PHP and MySQL for Dynamic Web Sites Intro Ed Crowley Class Preparation If you haven t already, download the sample scripts from: http://www.larryullman.com/books/phpand-mysql-for-dynamic-web-sitesvisual-quickpro-guide-4thedition/#downloads

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

CHIL CSS HTML Integrated Language

CHIL CSS HTML Integrated Language CHIL CSS HTML Integrated Language Programming Languages and Translators Fall 2013 Authors: Gil Chen Zion gc2466 Ami Kumar ak3284 Annania Melaku amm2324 Isaac White iaw2105 Professor: Prof. Stephen A. Edwards

More information

Lecture 12. PHP. cp476 PHP

Lecture 12. PHP. cp476 PHP Lecture 12. PHP 1. Origins of PHP 2. Overview of PHP 3. General Syntactic Characteristics 4. Primitives, Operations, and Expressions 5. Control Statements 6. Arrays 7. User-Defined Functions 8. Objects

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

The Java language has a wide variety of modifiers, including the following:

The Java language has a wide variety of modifiers, including the following: PART 5 5. Modifier Types The Java language has a wide variety of modifiers, including the following: Java Access Modifiers Non Access Modifiers 5.1 Access Control Modifiers Java provides a number of access

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Op. Use Description + x + y adds x and y x y

More information

SECTION II: LANGUAGE BASICS

SECTION II: LANGUAGE BASICS Chapter 5 SECTION II: LANGUAGE BASICS Operators Chapter 04: Basic Fundamentals demonstrated declaring and initializing variables. This chapter depicts how to do something with them, using operators. Operators

More information

The Arithmetic Operators

The Arithmetic Operators The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Examples: Op. Use Description + x + y adds x

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Important Points about PHP:

Important Points about PHP: Important Points about PHP: PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking,

More information

Lecture 7 PHP Basics. Web Engineering CC 552

Lecture 7 PHP Basics. Web Engineering CC 552 Lecture 7 PHP Basics Web Engineering CC 552 Overview n Overview of PHP n Syntactic Characteristics n Primitives n Output n Control statements n Arrays n Functions n WampServer Origins and uses of PHP n

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

3 The Building Blocks: Data Types, Literals, and Variables

3 The Building Blocks: Data Types, Literals, and Variables chapter 3 The Building Blocks: Data Types, Literals, and Variables 3.1 Data Types A program can do many things, including calculations, sorting names, preparing phone lists, displaying images, validating

More information

Web Scripting using PHP

Web Scripting using PHP Web Scripting using PHP Server side scripting No Scripting example - how it works... User on a machine somewhere Server machine So what is a Server Side Scripting Language? Programming language code embedded

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands Introduction Operators are the symbols which operates on value or a variable. It tells the compiler to perform certain mathematical or logical manipulations. Can be of following categories: Unary requires

More information

PHP by Pearson Education, Inc. All Rights Reserved.

PHP by Pearson Education, Inc. All Rights Reserved. PHP 1992-2012 by Pearson Education, Inc. All Client-side Languages User-agent (web browser) requests a web page JavaScript is executed on PC http request Can affect the Browser and the page itself http

More information

JME Language Reference Manual

JME Language Reference Manual JME Language Reference Manual 1 Introduction JME (pronounced jay+me) is a lightweight language that allows programmers to easily perform statistic computations on tabular data as part of data analysis.

More information

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web Web programming The PHP language Our objective Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web Access data inserted by users into HTML forms Interact

More information

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Java+- Language Reference Manual

Java+- Language Reference Manual Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( ) Sir Muhammad Naveed Arslan Ahmed Shaad (1163135 ) Muhammad Bilal ( 1163122 ) www.techo786.wordpress.com CHAPTER: 2 NOTES:- VARIABLES AND OPERATORS The given Questions can also be attempted as Long Questions.

More information

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. Preface p. xix Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. 5 Java Applets and Applications p. 5

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

easel LANGUAGE REFERENCE MANUAL

easel LANGUAGE REFERENCE MANUAL easel LANGUAGE REFERENCE MANUAL Manager Danielle Crosswell dac2182 Language Guru Tyrus Cukavac thc2125 System Architect Yuan-Chao Chou yc3211 Tester Xiaofei Chen xc2364 Table of Contents 1. Introduction...

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can

More information

ME 461 C review Session Fall 2009 S. Keres

ME 461 C review Session Fall 2009 S. Keres ME 461 C review Session Fall 2009 S. Keres DISCLAIMER: These notes are in no way intended to be a complete reference for the C programming material you will need for the class. They are intended to help

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

php Mr. Amit Patel Hypertext Preprocessor Dept. of I.T.

php Mr. Amit Patel Hypertext Preprocessor Dept. of I.T. php Hypertext Preprocessor Mr. Amit Patel Dept. of I.T..com.com PHP files can contain text, HTML, JavaScript code, and PHP code PHP code are executed on the server, and the result is returned to the browser

More information

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP? PHP 5 Introduction What You Should Already Know you should have a basic understanding of the following: HTML CSS What is PHP? PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open

More information

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments 2 Class Keyword class used to define new type specify

More information

Operators in C. Staff Incharge: S.Sasirekha

Operators in C. Staff Incharge: S.Sasirekha Operators in C Staff Incharge: S.Sasirekha Operators An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in C

More information

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C Overview The C Programming Language (with material from Dr. Bin Ren, William & Mary Computer Science) Motivation Hello, world! Basic Data Types Variables Arithmetic Operators Relational Operators Assignments

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

B. V. Patel Institute of BMC & IT 2014

B. V. Patel Institute of BMC & IT 2014 Unit 1: Introduction Short Questions: 1. What are the rules for writing PHP code block? 2. Explain comments in your program. What is the purpose of comments in your program. 3. How to declare and use constants

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science) The C Programming Language (with material from Dr. Bin Ren, William & Mary Computer Science) 1 Overview Motivation Hello, world! Basic Data Types Variables Arithmetic Operators Relational Operators Assignments

More information

Prasanth Kumar K(Head-Dept of Computers)

Prasanth Kumar K(Head-Dept of Computers) B.Sc (Computer Science) Object Oriented Programming with Java and Data Structures Unit-II 1 1. Define operator. Explain the various operators in Java. (Mar 2010) (Oct 2011) Java supports a rich set of

More information

AP Computer Science A

AP Computer Science A AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 2 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Java Notes. 10th ICSE. Saravanan Ganesh

Java Notes. 10th ICSE. Saravanan Ganesh Java Notes 10th ICSE Saravanan Ganesh 13 Java Character Set Character set is a set of valid characters that a language can recognise A character represents any letter, digit or any other sign Java uses

More information

UNIT-2 Introduction to C++

UNIT-2 Introduction to C++ UNIT-2 Introduction to C++ C++ CHARACTER SET Character set is asset of valid characters that a language can recognize. A character can represents any letter, digit, or any other sign. Following are some

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++ Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

COMS 469: Interactive Media II

COMS 469: Interactive Media II COMS 469: Interactive Media II Agenda Project One PHP Preview Project One Grading Methodology Return Project One & Evaluation Sheet Project One Evaluation Methodology Consider each project in and of itself

More information