Introduction
Portability :
Speed :
Open Source :
Extensible :
XML and Database Support :
"Hello World" Script in PHP :
Escaping to PHP:
|
Short-open (SGML-style) tags :
ASP-style tags :
<% ... %> |
HTML script tags:
|
Single-line comments:
# This is a comment, and # This is the second line of the comment // This is a comment too. Each style comments only print "An example with single line comments"; ?> Multi-lines comments: They are generally used to provide pseudocode algorithms and more detailed explanations when necessary. The multiline style of commenting is the same as in C. Here are the example of multi lines comments.
PHP is whitespace insensitive: Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and carriage returns (end-of-line characters). PHP whitespace insensitive means that it almost never matters how many whitespace characters you have in a row.one whitespace character is the same as many such characters For example, each of the following PHP statements that assigns the sum of 2 + 2 to the variable $four is equivalent:
PHP is case sensitive: Yeah it is true that PHP is a case sensitive language. Try out following example:
|
Variable capital is 100 Variable CaPiTaL is |
$greeting = "Welcome to PHP!"; |
Expressions are combinations of tokens:
Braces make blocks:
if (3 == 2 + 1) print("Good - I haven't totally lost my mind. "); if (3 == 2 + 1) { print("Good - I haven't totally"); print("lost my mind. "); } |
Running PHP Script from Command Prompt:
echo "Hello world !!!"; ?> |
$ php test.php |
- All variables in PHP are denoted with a leading dollar sign ($).
- The value of a variable is the value of its most recent assignment.
- Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
- Variables can, but do not need, to be declared before assignment.
- 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.
- Variables used before they are assigned have default values.
- PHP does a good job of automatically converting types from one to another when necessary.
- PHP variables are Perl-like.
- Integers: are whole numbers, without a decimal point, like 4195.
- Doubles: are floating-point numbers, like 3.14159 or 49.1.
- Booleans: have only two possible values either true or false.
- NULL: is a special type that only has one value: NULL.
- Strings: are sequences of characters, like 'PHP 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).
Integers:
$int_var = 12345; $another_int = -12345 + 12345; |
Doubles:
$many = 2.2888800; $many_2 = 2.2111200; $few = $many + $many_2; print(.$many + $many_2 = $few .); |
2.28888 + 2.21112 = 4.5 |
Boolean:
if (TRUE) print("This will always print "); else print("This will never print "); |
Interpreting other types as Booleans:
- If the value is a number, it is false if exactly equal to zero and true otherwise.
- If the value is a string, it is false if the string is empty (has zero characters) or is the string "0", and is true otherwise.
- Values of type NULL are always false.
- If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.
- Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).
- Don't use double as Booleans.
$true_num = 3 + 0.14159; $true_str = "Tried and true" $true_array[49] = "An array element"; $false_array = array(); $false_null = NULL; $false_num = 999 - 999; $false_str = ""; |
NULL:
$my_var = NULL; |
$my_var = null; |
- It evaluates to FALSE in a Boolean context.
- It returns FALSE when tested with IsSet() function.
Strings:
$string_1 = "This is a string in double quotes"; $string_2 = "This is a somewhat longer, singly quoted string"; $string_39 = "This string has thirty-nine characters"; $string_0 = ""; // a string with zero characters |
$variable = "name"; $literally = 'My $variable will not print!\\n'; print($literally); $literally = "My $variable will print!\\n"; print($literally); ?> |
My $variable will not print!\n My name will print |
- Certain character sequences beginning with backslash (\) are replaced with special characters
- Variable names (starting with $) are replaced with string representations of their values.
- \n is replaced by the newline character
- \r is replaced by the carriage-return character
- \t is replaced by the tab character
- \$ is replaced by the dollar sign itself ($)
- \" is replaced by a single double-quote (")
- \\ is replaced by a single backslash (\)
Here Document:
$channel =<<<_xml_ span=""> http://menu.example.com/ _XML_; echo << This uses the "here document" syntax to output multiple lines with variable interpolation. Note that the here document terminator must appear on a line with just a semicolon. no extra whitespace!
END; print $channel; ?> |
This will produce following result:
This uses the "here document" syntax to output multiple lines with variable interpolation. Note that the here document terminator must appear on a line with just a semicolon. no extra whitespace! http://menu.example.com/ |
Variable Scope:
Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types:
- Local variables
- Function parameters
- Global variables
- Static variables.
Local Variables:
A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function:
$x = 4; function assignx () { $x = 0; print "\$x inside function is $x. } assignx(); print "\$x outside of function is $x. ?> |
This will produce following result.
$x inside function is 0. $x outside of function is 4. |
Function Parameters:
Function parameters are declared after the function name and inside parentheses. They are declared much like a typical variable would be:
// multiply a value by 10 and return it to the caller function multiply ($value) { $value = $value * 10; return $value; } $retval = multiply (10); Print "Return value is $retval\n"; ?> |
This will produce following result.
Return value is 100 |
Global Variables:
In contrast to local variables, a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name.
Consider an example:
$somevar = 15; function addit() { GLOBAL $somevar; $somevar++; print "Somevar is $somevar"; } addit(); ?> |
This will produce following result.
Somevar is 16 |
Static Variables:
The final type of variable scoping that I discuss is known as static. In contrast to the variables declared as function parameters, which are destroyed on the function's exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again.
You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name.
function keep_track() { STATIC $count = 0; $count++; print $count; print " } keep_track(); keep_track(); keep_track(); ?> |
This will produce following result.
1 2 3 |
Variable Naming:
Rules for naming a variable is:
- Variable names must begin with a letter or underscore character.
- A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc
There is no size limit for variables.
Constants in PHP:
A constant is a name or an identifier for a simple value. A constant value cannot change during the execution of the script. By default a constant is case-sensitiv. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.
To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $. You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically.
constant() function:
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or returned by a function.
constant() example:
define("MINSIZE", 50); echo MINSIZE; echo constant("MINSIZE"); // same thing as the previous line ?> |
Only scalar data (boolean, integer, float and string) can be contained in constants.
Differences between constants and variables are:
- There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign.
- Constants cannot be defined by simple assignment, they may only be defined using the define() function.
- Constants may be defined and accessed anywhere without regard to variable scoping rules.
- Once the Constants have been set, may not be redefined or undefined.
Valid and invalid constant names:
// Valid constant names define("ONE", "first thing"); define("TWO2", "second thing"); define("THREE_3", "third thing") // Invalid constant names define("2TWO", "second thing"); define("__THREE__", "third value"); |
PHP Magic constants:
PHP provides a large number of predefined constants to any script which it runs.
There are five magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows:
A few "magical" PHP constants ate given below:
Name | Description |
__LINE__ | The current line number of the file. |
__FILE__ | The full path and filename of the file. If used inside an include,the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances. |
__FUNCTION__ | The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. |
__CLASS__ | The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. |
__METHOD__ | The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive). |
Operators in PHP
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.
- Arithmetic Operators
- Comparision Operators
- Logical (or Relational) Operators
- Assignment Operators
- Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmatic Operators:
There are following arithmatic operators supported by PHP language:
Assume variable A holds 10 and variable B holds 20 then:
Operator | Description | Example |
+ | Adds two operands | A + B will give 30 |
- | Subtracts second operand from the first | A - B will give -10 |
* | Multiply both operands | A * B will give 200 |
/ | Divide numerator by denumerator | B / A will give 2 |
% | Modulus Operator and remainder of after an integer division | B % A will give 0 |
++ | Increment operator, increases integer value by one | A++ will give 11 |
-- | Decrement operator, decreases integer value by one | A-- will give 9 |
Comparison Operators:
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Operator | Description | Example |
== | Checks if the value of two operands are equal or not, if yes then condition becomes true. | (A == B) is not true. |
!= | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (A <= B) is true. |
Logical Operators:
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Operator | Description | Example |
and | Called Logical AND operator. If both the operands are true then then condition becomes true. | (A and B) is true. |
or | Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. | (A or B) is true. |
&& | Called Logical AND operator. If both the operands are non zero then then condition becomes true. | (A && B) is true. |
|| | Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | !(A && B) is false. |
Assignment Operators:
There are following assignment operators supported by PHP language:
Operator | Description | Example |
= | Simple assignment operator, Assigns values from right side operands to left side operand | C = A + B will assigne value of A + B into C |
+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand | C += A is equivalent to C = C + A |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand | C -= A is equivalent to C = C - A |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand | C %= A is equivalent to C = C % A |
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax:
Operator | Description | Example |
? : | Conditional Expression | If Condition is true ? Then value X : Otherwise value Y |
Operators Categories:
All the operators we have discussed above can be categorised into following categories:
- Unary prefix operators, which precede a single operand.
- Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
- The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.
- Assignment operators, which assign a value to a variable.
Precedence of PHP Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2;
Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category | Operator | Associativity |
Unary | ! ++ -- | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %= | Right to left |
Decision making & Looping
Branching :
The two main structures for branching are if and switch. The if, elseif ...else and switch statements are used to take decision based on the different condition.
You can use conditional statements in your code to make your decisions. PHP supports following threedecision making statements:
- if...else statement - use this statement if you want to execute a set of code when a condition is true and another if the condition is not true
- elseif statement - is used with the if...else statement to execute a set of code if one of several condition are true
- switch statement - is used if you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
The If...Else Statement
If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.
Syntax
if (condition) code to be executed if condition is true; else code to be executed if condition is false; |
Example
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
$d=date("D"); if ($d=="Fri") { echo "Have a nice weekend!"; } else { echo "Have a nice day!"; } ?>
If you want to execute some code if one of several conditions are true use the elseif statement
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
If you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
The switch statement works in an unusual way. First it evaluates given expression then seeks a lable to match the resulting value. If a matching value is found then the code associated with the matching label will be executed or if none of the lables match then statement will will execute any specified default code.
Looping : Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
The for statement is used when you know how many times you want to execute a statement or a block of statements.
|
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.
Example 1 :
The following example makes five iterations and changes the assigned value of two variables on each pass of the loop:
$a = 0; $b = 0; for( $i=0; $i<5; $i++ ) { $a += 10; $b += 5; } echo ("At the end of the loop a=$a and b=$b" ); ?> |
This will produce following result:
At the end of the loop a=50 and b=25 |
Example 2 :
//The following code shows all prime numbers within the range of 1-100
$str=1;
$end=100;
$cntr=1;
$inr=1;
for($cntr=$str;$cntr<=$end;$cntr++)
{
for($inr=2;$inr<$cntr;$inr++)
{
if($cntr % $inr == 0)
{
echo "Not Prime No:= ".$cntr."
";
break;
}
else if($inr == $cntr-1)
{
echo " Prime No:= ".$cntr."
";
}
}
}
?>
The while loop statement
The while statement will execute a block of code if and as long as a test expression is true. If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.
Syntax
while (condition) { code to be executed; } |
Example 1 :
This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
$i = 0; $num = 50; while( $i < 10) { $num--; $i++; } echo ("Loop stopped at i = $i and num = $num" ); ?> |
This will produce following result:
Loop stopped at i = 1 and num = 40 |
Example 2 :
// following code shows whether the given number is palindrome or not.
$pal_Num=552055;
$cp_Pal=$pal_Num;
$cal_Pal=0;
while($cp_Pal > 1)
{
$cal_Pal = $cal_Pal * 10;
$cal_Pal = $cal_Pal + ($cp_Pal % 10);
//echo " Y=".$cal_Pal."
$cp_Pal = $cp_Pal / 10;
//echo "
X=".$cp_Pal;
}
if($pal_Num == $cal_Pal)
{
echo " ".$cal_Pal." is Palindrome
}
else
{
echo " ".$pal_Num." is not Palindrome
}
?>
The do...while loop statement
The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.
Syntax
do { code to be executed; }while (condition); |
Example :
$count = 45;
do
{
print(“count is $count
”);
$count = $count + 1;
}
while ($count <= 10);
prints the single line:
count is 45
The foreach loop statement
The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
Syntax
foreach (array as value) { code to be executed; } |
Example
Try out following example to list out the values of an array.
$array = array( 1, 2, 3, 4, 5); foreach( $array as $value ) { echo "Value is $value } ?> |
This will produce following result:
Value is 1 Value is 2 Value is 3 Value is 4 Value is 5 |
The break statement
The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.
Example
In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
$i = 0; while( $i < 100) { $i++; if( $i == 25 )break; } echo ("Loop stopped at i = $i" ); ?> |
This will produce following result:
Loop stopped at i = 25 |
The continue statement
The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.
Example
In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.
$array = array( 1, 2, 3, 4, 5); foreach( $array as $value ) { if( $value == 3 )continue; echo "Value is $value } ?> |
This will produce following result
Value is 1
Value is 2
Value is 4
Value is 5
Arrays
An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an index.
- Numeric array - An array with a numeric index. Values are stored and accessed in linear fashion
- Associative array - An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
- Multidimensional array - An array containing one or more arrays and values are accessed using multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be prepresented by numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function reference.
/* First method to create array. */ $numbers = array( 1, 2, 3, 4, 5); foreach( $numbers as $value ) { echo "Value is $value } /* Second method to create array. */ $numbers[0] = "one"; $numbers[1] = "two"; $numbers[2] = "three"; $numbers[3] = "four"; $numbers[4] = "five"; foreach( $numbers as $value ) { echo "Value is $value } ?> |
This will produce following result:
Value is 1 Value is 2 Value is 3 Value is 4 Value is 5 Value is one Value is two Value is three Value is four Value is five |
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
Example
/* First method to associate create array. */ $salaries = array( "mohammad" => 2000, "qadir" => 1000, "zara" => 500 ); echo "Salary of mohammad is ". $salaries['mohammad'] . " echo "Salary of qadir is ". $salaries['qadir']. " echo "Salary of zara is ". $salaries['zara']. " /* Second method to create array. */ $salaries['mohammad'] = "high"; $salaries['qadir'] = "medium"; $salaries['zara'] = "low"; echo "Salary of mohammad is ". $salaries['mohammad'] . " echo "Salary of qadir is ". $salaries['qadir']. " echo "Salary of zara is ". $salaries['zara']. " ?> |
This will produce following result:
Salary of mohammad is 2000 Salary of qadir is 1000 Salary of zara is 500 Salary of mohammad is high Salary of qadir is medium Salary of zara is low |
Multidimensional Arrays
A multi-dimensional 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. Values in the multi-dimensional array are accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three subjects:
This example is an associative array, you can create numeric array in the same fashion.
$marks = array( "mohammad" => array ( "physics" => 35, "maths" => 30, "chemistry" => 39 ), "qadir" => array ( "physics" => 30, "maths" => 32, "chemistry" => 29 ), "zara" => array ( "physics" => 31, "maths" => 22, "chemistry" => 39 ) ); /* Accessing multi-dimensional array values */ echo "Marks for mohammad in physics : " ; echo $marks['mohammad']['physics'] . " echo "Marks for qadir in maths : "; echo $marks['qadir']['maths'] . " echo "Marks for zara in chemistry : " ; echo $marks['zara']['chemistry'] . " ?> |
This will produce following result:
Marks for mohammad in physics : 35 Marks for qadir in maths : 32 Marks for zara in chemistry : 39 |
Simple Array Functions :
// following code will show you various functions of array
$x[0]=123;
$x['color']="green";
$x[40]="abc";
//$ary=array();
//echo $x[39];die();
$v=array(0=>123,'color'=>'green',40=>"abc");
$v1=array(12,13,14,15,16);
$t=array(3,5,7,9,0=>5,'color'=>"green",10,40=>"qbc",45);
//echo $t[41];die();
$a=range(2010,1990);
//print_r($a);
//die();
$tmp['fybca'][1][1]="ajay";
$tmp['fybca'][1][2]="sanjay";
$tmp['fybca'][2][10]="suuny";
$tmp['sybca'][1][2]="ravi";
$tmp['tybca'][1][3]="ajay";
print_r($tmp);die();
$tmp1=array('fybca'=>array(1=>array(1=>"ajay",2=>"sanjay"),2=>array(10=>"sunny")),"sybca"=>array(1=>array(2=>"ravi")));
//echo $tmp[0]mp1
//print_r($tmp);
//die();
// using array() construct
$a=array();
$a=array(1,2,"hqyxt",'d',5,8);
//echo $a[2];
$ary=array('color' => "green", 0 => "name" , 3 => 10);
echo $ary[3];
$t=array(0=>10, 1=> 20 , 30,40,50, 5=>60);
echo "
".$t[3];
$tmp['fruit']['red'][0]="apple";
$tmp['fruit']['red'][1]="lichhi";
$tmp['vegi'][0]="potato";
$tmp['vegi']['red'][1]="tometo";
echo $tmp['fruit'][0];
print_r($tmp);
//die();
$tmp1=array('fruit' => 0,'color'=>4);
echo "
";
print_r($tmp1);
//die();
// list()
$fruit_basket = array('apple', 'orange', 'banana',189,2,2);
list($red_fruit, $orange_fruit,$abc,$cc) = $fruit_basket;
//$red_fruit = $fruit_basket[0];
//$orange_fruit=$fruit_basket[1];
echo $cc."
";
//die();
echo "
Array status :".is_array($fruit_basket)."
";
//die();
echo count($fruit_basket)."
";
//die();
//unset($fruit_basket[0]);
//echo count($fruit_basket)."
";die();
$red_fruit1='orange';
print_r($fruit_basket);
echo count($fruit_basket)."
";
echo "in_array() -> ".in_array($red_fruit1, $fruit_basket);
//die();
//unset($fruit_basket);
//echo is_array($fruit_basket)." ss
";
//echo count($fruit_basket)."
";
//echo sizeof($fruit_basket)."
";
echo "
using current and next
";
echo "current() === > ".current($fruit_basket)."
";
echo "next() ===> ".next($fruit_basket)."
";
echo "current() === > ".current($fruit_basket)."
";
echo "prev() === > ".prev($fruit_basket)."
";
echo "end() === > ".end($fruit_basket)."
";//die();
reset($fruit_basket);
while ( $res = each($fruit_basket))
{
echo $res[0]." --> ".$res[1]."
";
}
reset($fruit_basket);
echo array_search("orange",$fruit_basket); // returns the key of specified value
die();
$tmp=range(1,10);
echo next($tmp)."
";
echo next($tmp)."
";
echo prev($tmp)."
";
echo end($tmp1)."
";
echo $fruit_basket;
// accessing array using foreach loop
foreach($fruit_basket as $d)
{
echo "
".$d;
}
?>
Advanced Array Functions :
// following is the list of some advanced array functions.
$ary1=array(1,2,3,4,5,0=>6);
$ary=array("name" => "xyz", "lname" => "abcd", "addr"=>"aaaa", "pin" => "009123",0=>4);
print_r($ary);
echo "
";
$n_ary=array_keys($ary); // returns array having all the keys of the specified array
print_r($n_ary);
echo "
";
$v_ary=array_values($ary); //returns array having all the values of the specified array
print_r($v_ary);
echo "
";
$v_ary=array_flip($ary); //returns array... it flips the key-values that is all the keys becomes values and all values
becomes keys
print_r($v_ary);
echo "
";
$v_ary=array_reverse($ary); //accept array as argument and return reverse array
print_r($v_ary);
echo "
";
//rand();
//$z=shuffle($ary1); //randomize the values
//echo $z;
print_r($ary1);
echo "
";
$v_ary=array_merge($ary,$ary1); //merge two array and returns new array
print_r($v_ary);
echo "
";
$str="this is php example";
$n_str=explode(" ",$str);// returns an array of specific string saparated by a given delimeter
print_r($n_str);
$o_str=implode("+",$n_str); //returns a string from the elements of an array
echo "
$o_str
";
$s_ary=array_slice($ary,1,-1); // same as substr excepts it operates on array
print_r($s_ary);
?>
String in PHP
Strings are sequences of characters that can be treated as a unit assigned to variables, given as input to functions, returned from functions, or sent as output to appear on your user’s Web page. The simplest way to specify a string in PHP code is to enclose it in quotes, whether single quotes (‘) or double quotes (“), like this:
$my_string = ‘A literal string’;
$another_string = “Another string”;
The difference between single and double quotes lies in how much interpretation PHP does of the characters between the quote signs before creating the string itself. If you enclose a string in single quotes, almost no interpretation will be performed; if you enclose it in double quotes, PHP will splice in the values of any variables you include, as well as make substitutions for certain special character sequences that begin with the backslash (\) character.
For example,
if you evaluate the following code in the middle of a Web page:
$statement = ‘everything I say’;
$question_1 =
“Do you have to take $statement so literally?\n
”;
$question_2 =
‘Do you have to take $statement so literally?\n
’;
echo $question_1;
echo $question_2;
It will give following output :
Do you have to take everything I say so literally?
Do you have to take $statement so literally?\n
The following example will give you an idea about various string functions used in php. Test it yourself, remove comment of die() function and test it section by section.
Example :
$sport='vollyball';
$a = "i will play $sport in the\t summer
";
echo $a;
//die();
//interpolation with curly braces
$sport1 = 'volly';
$b = "i will play {$sport1}ball in the summer
";
echo $b;
//die();
$c="i like cricket but ";
$c.=$b;
echo $c."
";
//die();
$my_string="Double";
echo $my_string[4]."
";
//die();
for($i=0;$i<6;$i++)
{
$s=$my_string{$i};
echo $s."
";
}
//die();
//------------------------------------------------------//
// heredoc in php
$str = <<<_AAAA
This is a
demo message
$my_string
with heredoc.
ashdfjasd
a;sjdajsdajsdasd
_AAAA; $cnt=1; if($cnt ==1) { echo $str; } else { echo 1; } //die(); //-----------------------------------------------------// /* example of substr function */ $str = "hello world"; echo strlen($str)."
"; echo $str."
"; echo substr($str,4)."
"; //die(); echo substr($str,4,4)."
"; //die(); echo substr($str,-7)."
"; //die(); echo substr($str,4,-2)."
"; //die(); echo substr($str,-4,-2)."
"; //die(); // ------------------------------------ // // examples of string searching // $str1 = " example of string searching "; echo $str1."
"; echo strrpos($str1,'s')."
"; //die(); echo strcmp("sbr","sar")."
"; //die(); echo strlen($str1)."
"; //die(); //-----------------------------------------------------// /// string cleanup functions /// $str2=chop($str1); echo strlen($str2)."
"; //die(); $str3=trim($str1); echo strlen($str3)."
"; //die(); $str4=ltrim($str1); echo strlen($str4)."
"; //die(); $str5=rtrim($str1); echo strlen($str5)."
"; //die(); //////////////////////////////////// // string replace functions ////// $str_replace1="burma is similer to rhodesia in at least one way."; $edit1=str_replace("rhodesia","zimbabwe",$str_replace1); $edit2=str_replace("burma","myanmar",$edit1); echo $edit2."
"; //die(); echo "
example of substr_replace function...
"; echo substr_replace("abcdefg","-",2,1)."
"; //die(); echo "
example of str_repeat function...
"; echo str_repeat("-",50)."
"; //die(); echo strrev("abc")."
"; //die(); echo strtolower("ABC asdas asdDasdasd")."
"; echo ucwords("this is an example of title case ")."
"; //die(); echo ucfirst("sdfsdf sggf fgsds Wsdfds"); //die(); //////////////////////////////////////// echo "
email"; $a= 500.45555; printf("%.2f",$a); $email = 'name@example.com'; $domain = strstr($email, '@'); echo "
".$domain; //die(); $t="
He said, \'i' m fine.\ These characters ($,*) are very special to me \n
"; echo "
".addslashes($t); echo "
".stripslashes($t); echo "
".quotemeta($t); ?> Passing Arguments
There are two ways the browser client can send information to the web server. Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand. Like, name1=value1&name2=value2&name3=value3 Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.
The GET Method : The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. http://www.sunnygajjar.com/index.html?name1=value1&name2=value2
The POST Method : The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.
Example : //following code shows how to pass data between pages using php's superglobal if(isset($_POST['submit'])) { $name=$_POST['t1']; $email=$_POST['t2']; echo $name."
"; echo $email; } else { ?> Name:
E-mail:
} ?> PHP Superglobal :
$_SERVER :- The $_SERVER superglobal gives access to the WebSphere sMash Server attributes and a few HTTP request attributes. The complete list of keys that are currently supported includes : $_SERVER['HTTP_ACCEPT_CHARSET'] - The value of the Acccept-Charset header $_SERVER['HTTP_USER_AGENT'] - The value of the User-Agent header $_SERVER['REMOTE_ADDR'] - The IP address of the client making the request $_SERVER['REMOTE_HOST'] - The host name of the client making the request $_SERVER['REMOTE_PORT] - The port number of the client making the request $_SERVER['SCRIPT_FILENAME'] - The file name of the script being invoked $_SERVER['SCRIPT_NAME'] - The name of the script being invoked $_SERVER['SERVER_PORT'] - The port number that the server accepted the request on $_SERVER['REQUEST_METHOD'] - The HTTP method of the request $_SERVER['REQUEST_URI'] - The URI associated with the HTTP request $_SERVER['REQUEST_TIME'] - The time stamp when the request was dispatched to the script
$_GET :- The $_GET variable is used to access URL query parameters associated with an HTTP request. URL query parameters are most commonly used for HTTP GET requests, but they are in fact supported for all HTTP request types. For the following request: /search?title=Rose&author=Eco $_GET['title'] will have the value "Rose" $_GET['author'] will have the value "Eco"
$_POST :- The $_POST variable is similar to the $_GET variable except that it processes the body of the HTTP POST request if the content type of the body is application/x-www-form-urlencoded.
$_COOKIE :- The $_COOKIE variable allows the script developer to query the cookies that were sent by the client for the request. If the cookie key uses the '[]' notation to denote an array accessor, the cookie values can be accessed through PHP arrays.
$_SESSION :- An associative array containing session variables available to the current script.
$_REQUEST :- The $_REQUEST variable provides the contents of the $_GET, $_POST, and $_COOKIE arrays. Note that if a parameter with the same name appears in two (or three) of the individual arrays, the value for that parameter in $_REQUEST is undefined.
$_FILES :- The $_FILES variable contains information about any files that were uploaded during the current HTTP request. Given the following HTML form: The $_FILES variable can be accessed by the following script: echo $_FILES['myfile']['name'] . "\n"; // name of the file on the client echo $_FILES['myfile']['type'] . "\n"; // content type - text/plain echo $_FILES['myfile']['size'] . "\n"; // file length echo $_FILES['myfile']['tmp_name'] . "\n"; // path to the temporary file on the server echo $_FILES['myfile']['error'] . "\n"; // error code ?>
you can add PHP to your HTML is by putting it in a separate file and calling it by using PHP’s include functions. There are four include functions: - include(‘/filepath/filename’)
- require(‘/filepath/filename’)
- include_once(‘/filepath/filename’)
- require_once(‘/filepath/filename’)
In previous versions of PHP, there were significant differences in functionality and speed between the include functions and the require functions. This is no longer true; the two sets of functions differ only in the kind of error they throw on failure. Include() and include_once() will merely generate a warning on failure, while require() and require_once() will cause a fatal error and termination of the script.
As suggested by the names of the functions, include_once() and require_once() differ from simple include() and require() in that they will allow a file to be included only once per PHP script. This is extremely helpful when you are including files that contain PHP functions, because redeclaring functions results in an automatic fatal error. In larger PHP systems, it’s quite common to include files which include other files which include other files — it can be difficult to remember whether you’ve included a particular function before, but with include_once() or require_once() you don’t have to.
Example :adsfsd sdfa
cookie stuff
show cookie stuff
Hello:
Your color:
");