Вы находитесь на странице: 1из 35

MCAE04, Web Programming with PHP and Ajax

Unit-I

1) Mention the unique features of php.


Php is one of the most popular server side scripting languages running today. it is used for creating dynamic web pages that interact with the user offering customized information. Php offers many advantages. It is vast fast stable ,secure easy to use and open source. Performance: scripts written in php execute faster than those written in other scripting languages. Portability: Php is available for many platforms and php programs are portable between platforms. This ability to easily undertake cross platform development is a valuable one especially when operating in multiplatform corporate environment. Ease of use: php is extremely sophisticated programming language. Its syntax is clear and consistent and comes with an exhaustive documentation and its one of the reasons that php is favored as a rapid prototyping tool for web based applications Open source: php is an open source project the project is developed by a worldwide team of volunteers who made its source code freely available on the web. Community support: php is a community supported language the access it offers to the creativity and imagination of hundreds of developers across the world, the php extension community library which contains hundreds of readymade widgets and extensions that developers can use to painlessly add new functionalities to php Third party support: php strength lies in its support for a wide range of different databases. Php 5.3 supports more than 15 different database engines, and it includes common API for database access. Php manages freeing all resources. Users do not require to free file handle resource, database resources memory resources etc unless programmer need to free resources during script execution. Php also has reference count feature. For eg., memory for variable is shared when it is assigned to other variable .if contents has been changed , Php allocates new memory for it. Various other unique features added in Php 5.3.0 are: Support for namespaces, late static binding, native closures. Magic constants and magic methods: Magic methods: _callstatic() and _invoke(). Magic constants: (_LINE_) FETCHES CURRENT LINE NO. (_FILE_): FETCHES FILE PATH. (_DIR_): DIRECTORY PATH. Using Glob keyword to find files, eg: $files=glob(*.php);

It does not just stop here either phps extensible architecture allows developers to write common add ons to the language ,with the result that php developers can today read and write the GIF,JPEG,PNG image formats send and receive e mails using the STMP,IMAP,POP3 protocols interface with web services using the REST & SOAP protocols ;and create and manipulate pdf documents .

MCAE04, Web Programming with PHP and Ajax

Unit-I

2) Write a short note on php variables?


A variable is simply a container thats used to store both numeric and non-numeric information. PHP has some simple rules for naming variables. They are: Every variable name must be preceded with a dollar($) symbol. Name must begin with a letter or underscore (_) character optionally followed by more letters, numbers or underscore characters. Punctuation marks such as commas, quotation marks, periods or spaces are not permitted in variable names. Variables names in PHP are case-sensitive.

Eg:- $root, $_num, $query2. Assigning values to variables:To assign the value to a variable simply use equality(=) symbol, which assigns the value on the right side of the equation to the variable on the left. You can also assign a variable the value of another variable. Eg :- <?php $n=10; $m=$n; print ($n); print ($m); ?> // O/p:- Both Prints 10. Unassigning variables:To destroy a variable, pass the variable which you want to destroy to a Php aptly named unset() function. Unset() function which takes the one parameter, which the variable you want to destroy and it destroy the variable and assign the value undefined. You can also empty the variable contents by using PHPs special NULL value. When you assign the NULL value to PHP variable it has empty. Syntax:- unset($var_name); $a=null; Inspecting variables:var_dump() function in php, which accepts a variable and X-rays it for you. This function tells you what a variable contains and also show the variables data type. Syntax:- var_dump($var_name); Eg:- $a=10; var_dump($a); //O/p:-which say value with its data type.
2

MCAE04, Web Programming with PHP and Ajax

Unit-I

3) Explain the data types in PHP with example.


Ans: PHP has 8 data types in which 4 are scalar types: - Boolean, integer, double and string, 2 compound types: - array and object and 2 special types:- resource and NULL. Because PHP is dynamically typed, it has no type declarations. An unassigned variable is called an unbound variable, has the value NULL, which is the only value of NULL type. To check whether the value of a variable is NULL or not NULL we use isset() function. For example: isset ($a) returns true if $a currently has a not-NULL value , false otherwise. Integer type This type corresponds to the long type of C and its successors, which means its size is that of the word size of the machine on which the program is run. In most cases, this is 32 bits or a bit less than ten decimal digits. Double types PHP double type corresponds to double type in C. Decimal literals can include a decimal point, an exponent or both. There is no need to any digit before or after the decimal point, so both .345 and 345. are legal double literals. String type Characters in PHP are single byte. There is no character type. String literal are defined with either single() or double quotes() delimiters. In single-quoted string literals, escape sequences such as \n, are not recognized and values of embedded variables are not substituted (interpolated). In double quoted string literals, escape sequence are recognized and embedded variables are replaced by their current value. $sum=10.2; The sum is: $sum But for, The sum is: $sum //Output will be, The sum is 10.2 If you do not want any character to be interpolated, precede the first character of the name (the dollar-sign) with a backslash (\). Boolean type The only two possible values for the Boolean type are True and False, both of which are case sensitive. If an integer expression is used in Boolean context, it evaluates to False if it is zero; otherwise it is true. If a string expression is used in Boolean context, it evaluates to False if it either the empty string 0; otherwise, it is True. Even 0.0 evaluates to True. //Output will be exactly the same

MCAE04, Web Programming with PHP and Ajax

Unit-I

4) List the php functions to test variable data types and explain them with example. (6M)
In other programming languages, a variables data type must be explicitly defined by the programmer but in PHP a variables data types is automatically determined by the content it holds and if the variables content changes over the duration of a script, PHP will automatically set the variable to the appropriate new data type. PHP has a function, gettype(), using which we can find out the type of a particular variable. In the following example, the variable $whoami defined as a string, then the variable is de-initialized with the unset() method, which removes its value and turns it into a NULL. Example : <?PHP $whoami = sarah; echo gettype($whoami); //output : string unset ($whoami); echo gettype($whoami); //output : null; ?> PHP internally resets the data type of $whoami from string to NULL. However, its possible to explicitly set the type of PHP variables by casting a variable to a specific type before using it. Example : <?PHP $speed = 501.789; $new speed = (integer) $speed; echo $new speed; //Output : 501 ?> In addition to the gettype() function, PHP includes a number of more specialized functions, to test if a variable is of specific type. 1. is_bool() 2. is_numeric() 3. is_int() 4. is_float() 5. is_string() 6. is_null() 7. is_array() 8. is_object() //Tests if a variable holds a Boolean value //Tests if a variable holds a Numeric value //Tests if a variable holds an Integer value //Tests if a variable holds a floating-point value //Tests if a variable holds a string value //Tests if a variable holds a NULL value //Tests if a variable is an array //Tests if a variable is an object

All the above mentioned functions take a variable name as parameter and returns true or false.

MCAE04, Web Programming with PHP and Ajax

Unit-I

5) How do you define a constant in PHP? Explain with an example.


Definition The define() function defines a constant. Constants are much like variables, except for the following differences:

(2M)

A constant's value cannot be changed after it is set Constant names do not need a leading dollar sign ($) Constants can be accessed regardless of scope Constant values can only be strings and numbers

Syntax define(name, value, case_insensitive)

Parameter name value case_insensitive

Description Required. Specifies the name of the constant Required. Specifies the value of the constant Optional. Specifies whether the constant name should be case-insensitive. If set to TRUE, the constant will be case-insensitive. Default is FALSE (case-sensitive)

Example 1 Define a case-sensitive constant: <?php define("GREETING", "Hello you! How are you today?"); echo constant("GREETING"); ?> The output of the code above will be: Hello you! How are you today? Example 2 Define a case-insensitive constant: <?php define("GREETING", "Hello you! How are you today?", TRUE); echo constant("greeting"); ?> The output of the code above will be: Hello you! How are you today?
5

MCAE04, Web Programming with PHP and Ajax

Unit-I

6) Explain the operators in php with example. (10M)


The operators in php are the same as the C/C++ operators. These operators can be categorized into the following. Arithmetic Operators Assignment Operators Comparison Operators String Operators Arithmetic Operators Example Name -$a $a + $b $a - $b $a * $b $a / $b $a % $b Negation Addition Subtraction Result Opposite of $a. Sum of $a and $b. Difference of $a and $b.

Multiplication Product of $a and $b. Division Modulus Quotient of $a and $b. Remainder of $a divided by $b.

Assignment Operator The basic assignment operator is "=". It means that the left operand gets set to the value of the expression on the right side. $a = 4; //assign 4 to variable a $b = $a / /assign the value of variable a to b

Comparison Operators Example $a == $b Name Equal Result TRUE if $a is equal to $b after type juggling. TRUE if $a is equal to $b, and they are of the same type. TRUE if $a is not equal to $b. TRUE if $a is not equal to $b, or they are not of the same type. TRUE if $a is less than $b.
6

$a === $b Identical $a != $b $a !== $b $a < $b Not equal Not identical Less than

MCAE04, Web Programming with PHP and Ajax

Unit-I

Comparison Operators Example $a > $b $a <= $b $a >= $b Name Greater than Less than or equal to Result TRUE if $a is greater than $b. TRUE if $a is less than or equal to $b.

Greater than or equal to TRUE if $a is greater than or equal to $b.

Increment/decrement Operators Example Name ++$a $a++ --$a $a-Pre-increment Post-increment Pre-decrement Effect Increments $a by one, then returns $a. Returns $a, then increments $a by one. Decrements $a by one, then returns $a.

Post-decrement Returns $a, then decrements $a by one.

Logical Operators Example Name Result TRUE if both $a and $b are TRUE. TRUE if either $a or $b is TRUE. TRUE if either $a or $b is TRUE, but not both. TRUE if $a is not TRUE. TRUE if both $a and $b are TRUE. TRUE if either $a or $b is TRUE.

$a and $b And $a or $b $a xor $b ! $a $a && $b $a || $b Or Xor Not And Or

MCAE04, Web Programming with PHP and Ajax

Unit-I

String Operators There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.

MCAE04, Web Programming with PHP and Ajax

Unit-I

7) How to retrieve form data in php? (6M)


With HTML, there are two commonly used methods GET and POST for passing data from one page to another. In php there are two arrays, $_GET and $_POST, which are used to process the form data. These arrays that are automatically created and filled with the form data. We can use either single or double quotes with the name of the form element to retrieve the value of that form data. For e.g: Here, is an html login form with text field, name and password whose data values are retrieved using $_POST and the appropriate action is performed. HTML Form: <html> <head><title>Form Processing</title> </head> <body> <form action=process.php method=post> <label>Enter Name:<input type=text name=user_name /></label><br /> <label>Enter Password:<input type=password name=password /></label><br /> <input type=submit value=submit /> </form> </html> process.php <?php $user=$_POST*user_name+; $pass=$_POST*password+; If (strcmp($user,mca)==0) { If((strcmp($pass,third)==0) { echo Welcome to 3rd sem, MCA; } } else echo Invalid user name or password; ?> This example compares the entered user name with mca and the entered password with third. If both the values are matched, then a welcome message is printed on the screen. The same action can be performed using $_GET, by changing the method value of the form to GET.

MCAE04, Web Programming with PHP and Ajax

Unit-I

8) Explain conditional statements in PHP with example. (7M)


Conditional statements are the set of commands used to perform different actions based on different conditions. The different types of conditional statements that are available in PHP are: if, if-else, if-elseif-else statements switch statements If statement: The PHP if statements checks if the given condition is true. If the given condition turns true then the block of statements gets executed. If condition is false, then the given block of statements does not get executed. Syntax: if(<condition>) { } Ex: $num=1; if($num>0) { echo Is a positive number; } If-else statement: The PHP if-else statements checks if the given condition is true or false. If the given condition turns true then the statements of if block gets executed. If the given condition is false, then the statements of else block gets executed. Syntax: if(<condition>) { } else { } Ex: $num=1; if($num>0)
10

block of statements;

statement1; statement2;

statement3; statement4;

MCAE04, Web Programming with PHP and Ajax

Unit-I

{ echo Is a positive number; } else { echo Is a negative number; } If-elseif-else statement: The PHP if-elseif-else statements checks for multiple conditions. We can check for as many as conditions we want by placing them in elseif block. It helps in checking many conditions and execute appropriate block. Syntax: if(<condition>) { } elseif(<condition>) { } else { } Ex: $num=1; if ($num>0) { echo number is greater than zero; } elseif ($num<0) { echo is a negative number; } else { echo number is zero;
11

block1 of statements;

block2 of statements;

block3 of statements;

MCAE04, Web Programming with PHP and Ajax

Unit-I

} Switch statement: Switch statements work the same as if statements. The difference is that they can check for multiple values. Of course you do the same with multiple if..else statements, but this is not always the best approach. A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. The syntax for the switch statement as follows: Syntax: switch(expression) { case label1: statements1; break; case label2: statements2; break; ......... default: Statements; } Ex: $num=1; switch($num) { case 1: echo odd number; break; case 2: echo even number; break; case 0: echo Zero!!!; break; default: echo wrong input; break; }

12

MCAE04, Web Programming with PHP and Ajax

Unit-I

9) Explain iterative statements in php with example. (10M)


Like any good programming language, PHP also supports loops - essentially, the ability to repeat a series of actions until a prespecified condition is fulfilled. Loops help in automating repetitive tasks within a program. PHP supports four different types of loops. They are : The while Loop: while loop repeats continuously while a prespecified condition is true. If the conditional expression evaluates to false on the first pass itself, the loop will never executed. Here's an example, which uses a loop to repeatedly print 'x' to the output page. <?php // repeat continuously until counter becomes 10 // output: 'xxxxxxxxx' $counter = 1; while ($counter < 10) { echo 'x'; $counter++; } ?> The condition enclosed in parentheses; so long as this condition evaluates to true, the code within the curly braces is executed. As the condition becomes false, the loop stops repeating, and the lines following the loop are executed in the usual fashion. The do-while Loop: do-while loop evaluates the condition at the end of each loop iteration. The condition to be evaluated appears at the bottom of the loop block, rather than beginning. The loop will always be executed once, even if the conditional expression is false, because the condition is evaluated at the end of the loop iteration. For example, <?php //repeat continuously until counter becomes 10 //output: 'xxxxxxxxx' $counter = 1;
13

MCAE04, Web Programming with PHP and Ajax

Unit-I

do { echo 'x'; $counter++; } while ($counter < 10); ?> The for Loop: for loop is useful when you need to execute a set of statements a specific number of times. There are three expressions involved in the typical for loop, seperated by semicolons and enclosed in parentheses. The first of these is an assignment expression, which initializes the loop counter with a specific value. The second is a conditional expression, which must evaluate to either true or false; the loop will continue to execute so long as this condition remains true. Once the condition becomes false, the loop will stop executing. The third is again an assignment expression,which is executed at the end of each loop iteration, and which updates the loop counter with a new value. For example, <?php // repeat continuously until counter becomes 10 // output: 123456789 for($x=1; $x<10; $x++) { echo "$x"; } ?> In this listing , loop begins by initializing the counter variable $x to 1; it then execuutes the statements that make up the loop. Once it reaches the end of the first loop iteration, it updates the loop counter by adding 1 to it, checks the conditional expression to ensure that the counter hasn't yet reached 10 and the conditional expression becomes false. Combining loops: It is possible to nest one loop inside another. To illustrate, consider the example, which nests one for loop inside another to dynamically generate an html table. <html>
14

MCAE04, Web Programming with PHP and Ajax

Unit-I

<head> <title></title> </head> <body> <?php //generate an HTML table // 3 rows, 4 columns echo "<table border=\"1\">"; for($row=1; $row<4; $row++) { echo "<tr>"; for($col=1; $col<5; $col++) { echo "<td>Row $row, Column $col</td>"; } echo "</tr >"; } echo"</table>"; ?> </body> </html> This script utilizes two for loops. The end result is a table with three rows, each containing four cells. The foreach Loop: foreach is the simplest way of iterating over arrays. With a foreach loop, each time the loop runs, the current array element is assigned to a temporary variable, which can be processed in any way you pleaseprinted, copied to another variable and so on. Unlike a for loop, a foreach loop doesn't use a counter; it automatically "knows" where it is in the array, and it moves forward continuously until it reaches the end of the array, at which point if automatically halts. For example, <?php //define array
15

MCAE04, Web Programming with PHP and Ajax

Unit-I

$cities = array('London' , 'Paris' , 'Madrid' , 'Los Angeles' , 'Bombay' , 'Jakarta'); // iterate over array //print each value foreach ($cities as $c) { echo "$c \r\n"; } ?> The foreach loop also works with associative arrays, except that for such arrays, it uses two temporary variables(one each for the key and value). For example, <?php //define array $cities = array{ "United Kingdom" => "London", "United States" => "Washington", "France" => "Paris", "India" => "Delhi"; }; //iterate over array //print each value foreach ($cities as $key => $value) { echo "$value is in $key. \r\n"; } ?>

16

MCAE04, Web Programming with PHP and Ajax

Unit-I

10) Demonstrate the use of Break and Continue in PHP? (5M) Or Compare and contrast break and continue with example.
Break and Continue are used inside the loop statements such as for, foreach, while, do-while or switch . CONTINUE Continue statement is used to continue the loop to next iteration. In this case all code after continue will not be executed. i.e. Continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration. For example :To print only odd number in range 1 to 10 using continue. <? php for($i = 1; $i <= 10; $i++) { if ($i % 2 == 0) continue; echo $i; } ?> output:- 1 3 5 7 9 Break On the other hand, break statement is used for stopping the current loop. The break statement exits from the for, foreach, while, do-while or switch statements. For example :If we want to stop the loop when $i > 10 <?php $i=1; while (true) { echo $i; If ($i > 10) break; $i++; } ?> output: 1 2 3 4 5 6 7 8 9 10

17

MCAE04, Web Programming with PHP and Ajax

Unit-I

11) Mention any ten string functions and explain its usage with example (10M)
Ans : Ten commonly used string functions are as follows:1. strchr()- The strchr() function is a case-sensitive function which searches for the first occurrence of string inside another string . It returns the rest of the string (from the matching point), or FALSE, if the string being searched for is not found. Its an alias of strstr() function . For case-insensitive search stristr() function can be used. Example:<?php echo strchr(MSRIT MCA third sem,MCA); ?> 2. ord()-The ord() function returns the ASCII value of the first character of the string. Example: <?php Echo ord(h).<br/>; Echo ord(hello).<br/>; ?> 3.strcasecmp()- The strcasecmp() is a case-insensitive function compares two strings This function returns: zero - if the two strings are equal. <0 - if string1 is less than string2. >0 - if string1 is greater than string2. For case sensitive comparison strcmp() function can be used. Example:<?php echo strcasecmp("MSRIT MCA","Msrit Mca"); ?> OUTPUT: 0 OUTPUT: 104 104

OUTPUT: MCA third sem

18

MCAE04, Web Programming with PHP and Ajax

Unit-I

4.strpos()-strpos() is a case-sensitive string function which returns the first occurrence of a sub string inside another string. If the sub string is not found false is returned. Another function similar to stopos() is strrpos() which returns the last occurrence of the sub string. This function takes 3 parameters: String- Specifies the string to be searched. Sub string- Specifies the string to be found. Start (Optional)- Specifies the position from where the search is to be started. OUTPUT:
3

Example:<?php echo strpos("MSRIT MCA","IT"); ?>

5.substr()- The substr() function returns a part of string. It takes 3 parameters :(i)String the string from which a specific part(substring) is to be returned (ii)Start-specifies the position from which the substring is to be returned. This parameter can take three different types of values 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 (iii)length (Optional). Specifies the length of the string to be returned. Default is to the end of the string. A positive number - The length to be returned from the start parameter A Negative number - The length to be returned from the end of the string. Example:<php echo substr("MSRIT MCA THIRD SEM",6); echo "<br/>"; echo substr("MSRIT MCA THIRD SEM ",6,5); echo "<br/>"; echo substr(MSRIT MCA THIRD SEM ",6,-3); echo "<br/>"; echo substr("MSRIT MCA THIRD SEM ",6,-4); >? 6.strtoupper()-The strtouppper() function converts a string to upper case. Another function similar to strtoupper() is strtolower() which converts the string supplied to it as parameter to lower case.
19

OUTPUT: MCA THIRD SEM MCA T MCA THIRD MCA THIR

MCAE04, Web Programming with PHP and Ajax

Unit-I

Ex:<?php echo strtoupper("String functions"); ?> 7. strrev()-The strrev() function reverses a string. Example:<?php echo strrev("String functions"); ?> OUTPUT: snoitcnuf gnirtS OUTPUT STRING FUNCTIONS

8.strlen()- The strlen() function returns the length of the string. Example:<?php echo strrev("String functions"); ?> 16 OUTPUT:

9. Str_repeat()-Using this function a string can be repeated a specified no. of times. Example:<?php for($i=1;$i<=5;$i++) { echo str_repeat("*",$i); echo "<br>"; } ?> 10.trim()- The trim() function removes whitespace and other predefined characters from both sides of the string .it takes two parameters as input- string and char(optional) which specifies which character to be removed from the string .if no character is specified as second parameter all of the following characters are removed"\0" NULL "\t" tab "\n" - new line "\x0B" - vertical tab "\r" - carriage return " " - ordinary white space OUTPUT: * ** *** **** *****

20

MCAE04, Web Programming with PHP and Ajax

Unit-I

Two functions similar to trim are ltrim and rtrim.ltrim() removes predefined characters from left side of the string while rtrim() removes predefined characters from the right side of the string. Example:<php $str = " MCA THIRD SEM "; echo "Without trim: " . $str; echo "<br />"; echo "With trim: " . trim($str); ?> OUTPUT:
Without trim: MCA THIRD SEM With trim: MCA THIRD SEM

21

MCAE04, Web Programming with PHP and Ajax

Unit-I

13) Explain the concept of arrays in php with example? (10M)


Ans) Array is collection of similar elements stored in consecutive memory locations. Array variables are special because they can hold more than one value at a time. Arrays are created in php by array() language construct. There are two types of arrays in php: 1)scalar arrays or indexed array . 2) Associative arrays. 1) Scalar arrays the indexer of the array which is used to determine the position of the stored data element is an integer which begins with zero. This type of array can be created using array() as $var-name=array(list of values); Here var-name is an array which will have elements mentioned in the list of values. Eg $fruits=array(apple, banana, pineapple); Here fruits is an indexed array which has apple, banana, and pineapple as its elements. Apple is stored at 0 th position, banana in 2nd and pineapple at 3rd. Thus we can access the value apple from preceding array, we use the notation $fruits[0],while pineapple can be retrieved as $fruits[2]. 2) Associative array In associative array ,the indexer or the key which is used to refer the data element is a string but not an integer.this type of array can be created as: $var-name=array( key1=>value, key2=>value, key3=>value, key4=>value, key5=>value,..keyN=>value); here var-name is an associative array,key1,.keyN are keys which are strings and refer to values associated with it. The keys of the array must be unique; each key references a single value and the key-value relationship is expressed through => symbol. Eg $fruits=array( a=>apple, b=>banna, c=>pineapple); To access the value apple from the array, we use notation $fruits*a+, while banana as $fruits*b+. 3) Multidimensional Arrays In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Example In this example we create a multidimensional array, with automatically assigned ID keys: $families = array (Griffin=>array ( Akki,Pats, Maks),
22

MCAE04, Web Programming with PHP and Ajax

Unit-I

Jimmi=>array (Glenn ), Brown=>array (Cleveland, Loretta,Junior)); The array above would look like this if written to the output: array ([Griffin]=>array ([0] => Akki [1] => Pats [2] => Maks ) [Jimmi] => array ([0] => Glenn) [Brown]=>array ([0] => Cleveland [1] => Loretta [2] => Junior))

23

MCAE04, Web Programming with PHP and Ajax

Unit-I

14) Explain array processing with loops and iterators with example.

(6M)

There are two types of arrays in php, scalar arrays and associative array. These arrays are operated using loops like for loop, foreach loop and iterators. Array processing using for loop: Example: <?php $seasons=array(Autumn, Winter, Spring, Summer); for($i=0; $i<4; $i++){ echo $seasons*$i+. ; } ?> Here the array elements are displayed on the screen with the help of for loop. Since for loop iterates depending on the assignment expression and the condition, here loop iterates from 0 to 3 over $seasons array and prints each value found. Array processing using foreach loop: Foreach loop each time runs by assigning the current array element to a temporary variable, which can then be processed. Unlike a for loop, a foreach loop doesnt use a counter; it automatically knows where it is in the array, and it moves forward continuously until it reaches the end of the array, and halts automatically. Example: <?php $seasons=array(Autumn,Winter,Spring,Summer); Foreach($seasons as $s) Echo $s ; } ?> The foreach loop also works with associative arrays. For these arrays it uses 2 temporary variables one for key and other for value. Example: <?php $cities = array{ "United Kingdom" => "London", "United States" => "Washington", "France" => "Paris", "India" => "Delhi";
24

MCAE04, Web Programming with PHP and Ajax

Unit-I

}; foreach($age as $key=>$value) Echo $keys age is $value. \n; ?> The Array iterative Statement: This provides a ready-made, extensible tool to loop over array elements. <?php //define array $cities = array{ "United Kingdom" => "London", "United States" => "Washington", "France" => "Paris", "India" => "Delhi"; }; //create an ArrayIterator object $iterator = new ArrayIterator ($cities); // rewind to beginning of array $iterator->rewind(); //iterate over array //print each value while( $iterator->valid()) { print $iterator->current(). " is in" . $iterator->key() . ". \r\n"; $iterator->next(); } ?> In this listing, an ArrayIterator object is initialized with an array variable, and the object's rewind() method is used to reset the internal array pointer to the first element of the array. A while loop, which runs as long as a valid() element exists, can then be used to iterate over the array. Individual array keys are retrieved with the key() method, and their corresponding values are retrieved with the current() method. The next() method moves the internal array pointer forward to the next array element.
25

MCAE04, Web Programming with PHP and Ajax

Unit-I

15) Mention any 10 array functions In PHP and explain its usage with examples. (10M)
1. Sort() : To sort both scalar and associative array elements , php provides six functions. Functions to sort scalar array elements are: a)sort($array_name) : This function sorts the array by value, sorted with numbers first ascending, then uppercase letters alphabetically, then lowercase letters alphabetically. The keys are re-assigned with appropriate numbers. Example: $arr = array(2,5,4,3,1,7); print(Unsorted array is); for($i=0;$i<6;$i++) { Print $arr[i]; } Sort($arr); Print(Sorted array is); for($i=0;$i<6;$i++) { Print $arr[i]; } Output: Unsorted array is: 2 5 4 3 1 7 Sorted array is: 1 2 3 4 5 7 b)rsort ($array_name) : This function sorts the array by value, sorted by lowercase letters first descending , then uppercase letters descending and lastly numbers descending. Example: $arr = array(2,5,4,3,1,7); print(Unsorted array is); for($i=0;$i<6;$i++) { Print $arr[i]; } rsort($arr); Print(Sorted array is); for($i=0;$i<6;$i++)
26

MCAE04, Web Programming with PHP and Ajax

Unit-I

{ Print $arr[i]; } Output: Unsorted array is: 2 5 4 3 1 7 Sorted array is: 7 5 4 3 2 1 Functions to sort Associative array are: c)asort($array_name) : This function sorts the associative array by value, sorted by lowercase letters first descending , then uppercase letters descending and lastly numbers descending. Example: $username['John']="Elmafudd"; $username['Alieza']="8hamper"; $username['Brian']="aopper24"; $username['Mary']="11_daper"; Print (Unsorted associativearray); foreach($username as $key_name => $key_value) { print $username[$key_value]; } asort($username); print(Sorted associative array is); foreach($username as $key_name => $key_value) { print $username[$key_value]; } After Sorting: $username['Mary']=11_daper $username['Alieza']=8hamper $username['John']=Elmafudd $username['Brian'] = aopper24 Output: 11_daper
27

MCAE04, Web Programming with PHP and Ajax

Unit-I

8hamper Elmafudd aopper24 d)arsort($array) : This function sorts the array by value, sorted by lowercase letters first descending , then uppercase letters descending and lastly numbers descending. Example: $username['John']="Elmafudd"; $username['Alieza']="8hamper"; $username['Brian']="aopper24"; $username['Mary']="11_daper"; Print (Unsorted associativearray); foreach($username as $key_name => $key_value) { print $username[$key_value]; } arsort($username); print (Sorted associative array is); foreach($username as $key_name => $key_value) { print $username[$key_value]; } After Sorting: $username['Brian'] = aopper24 $username['John'] = Elmafudd $username['Alieza'] = 8hamper $username['Mary'] = 11_daper Output: aopper24 Elmafudd 8hamper 11_daper
28

MCAE04, Web Programming with PHP and Ajax

Unit-I

e)ksort($array_name) : This function sorts an array by key. Each value's original key is retained. Example: $username['John']="Elmafudd"; $username['Alieza']="8hamper"; $username['Brian']="aopper24"; $username['Mary']="11_daper"; ksort($username); The array is now. $username['Alieza'] = 8hamper $username['Brian'] = aopper24 $username['John'] = Elmafudd $username['Mary'] = 11_daper f)krsort($array_name) : This function sorts an array by key in reverse order. Each value's original key is retained. Example: $username['John']="Elmafudd"; $username['Alieza']="8hamper"; $username['Brian']="aopper24"; $username['Mary']="11_daper"; krsort($username); The array is now. $username['Mary'] = 11_daper $username['John'] = Elmafudd $username['Brian'] = aopper24 $username['Alieza'] = 8hamper 2) count ($array_name) : This function returns size or length of array. Example: $arr= array(php,ajax,web); $count1 = count($arr);
29

MCAE04, Web Programming with PHP and Ajax

Unit-I

Print(Size is); Print($count1); Output: Size is 3 3.explode()This function splits a string into array elements. Syntax : explode(separator,string,limit)

separator string limit Example:

Required. Specifies where to break the string Required. The string to split Optional. Specifies the maximum number of array elements to return

$str= MCA MSRIT MBA; $arr = explode( ,$str); Print_r ($arr); Output: $arr[0]=MCA $arr[1]=MSRIT $arr[2]=MBA 4.implode(): This function joins array elements into a string. Syntax: implode(separator,array) Parameter separator array Example:
30

Description Optional. Specifies what to put between the array elements. Default is "" (an empty string) Required. The array to join to a string

MCAE04, Web Programming with PHP and Ajax

Unit-I

$arr= array(MCA,MSRIT,MBA); $str=implode(or,$arr); Print($str); Output: MCAor MSRITorMBA 5.range(): 1. This function creates an array containing a range of elements. 2.returns an array of elements from low to high. Syntax: range(low, high, step) Low: Required, Specifies the lowest value of the array. High :Required, Specifies the highest value of the array. Step: Optional, Specifies the increment used in the range. Default is 1 Example 1: $number=range(0,5); print_r ($number); The output of the above code will be: Array ( [0]=>0 [1]=>1 [2]=>2 [3]=>3 [4]=>4 [5]=>5 )

Example 2:

31

MCAE04, Web Programming with PHP and Ajax

Unit-I

$number=range(0,50,10); print_r($number); The output of the code above will be: Array ( [0]=>0 [1]=>10 [2]=>20 [3]=>30 [4]=>40 [5]=>50 ) 6.min(): This function is used to find the smallest element in an array. Example: $arr= {1,3,2,4,5,}; $m=min($arr); Print($m); Output: 1 7 max():. This function is used to find the largest element in an array. Example: $arr= {1,3,2,4,5,}; $m=max($arr); Print($m); Output: 5 8.shuffle(): 1.This function randomizes the order of the elements in the array. 2.Assigns new keys for the elements in the array. Existing keys will be removed. 3.Returns TRUE on success, or FALSE on failure. Syntax: shuffle($array) Parameter array Description Required. Specifies the array to use
32

MCAE04, Web Programming with PHP and Ajax

Unit-I

Example $arr=array("a"=>"Dog", "b"=>"Cat", "c"=>"Horse"); shuffle($arr); print_r($arr); After Shuffling(Internally): Array ( [0]=>Cat, [1]=>Horse, [2]=>Dog ) Output: Cat Horse Dog 9.array_slice(): This function extracts a segment of array. Syntax: array_slice(array, start, length, preserve) Parameter Array Start Description Required. Specifies an array Required. Numeric value. Specifies where the function will start the slice. 0 = the first element. If this value is set to a negative number, the function will start slicing that far from the last element. -2 means start at the second last element of the array. Optional. Numeric value. Specifies the length of the returned array. If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter. Optional. Possible values:

Length

Preserve

true - Preserve keys false - Default - Reset keys

Example1: $arr=array(one, two, three, four, five); $arr1=array(); $arr1=array_slice($arr,2,3); print_r($arr1); Output:
33

MCAE04, Web Programming with PHP and Ajax

Unit-I

Three four five Example2: with negative range $arr1=array_slice($arr,-3,3); Print_r($arr1); Output: Three two one 10. To insert elements in array there are two functions: a) array_unshift (): This function adds an element at the beginning of an array. Example: $arr=array (jan,feb,mar,apr,june); array_unshift($arr, dec); print_r ($arr); Output: dec jan feb mar apr june b) array_push():This function adds an elements at the end of an array. Example: $arr=array(jan,feb,mar,apr); array_push($arr,may); output: jan feb mar apr may 11.To remove an element from array there are two functions: a) array_ shift() : This function removes an element from begging of the array. Example: $arr=array(pq,rs,tu); $m=array_shift($arr) Print(Element removed is + $m); Print_r($arr); Output: Element removed is pq. rs tu. a)array_ pop() : This function removes an element from end of the array. Example:
34

MCAE04, Web Programming with PHP and Ajax

Unit-I

$arr=array(pq,rs,tu); $m=array_pop($arr) Print(Element removed is + $m); Print_r($arr); Output: Element removed is tu Pq rs

35

Оценить