Basic of PHP
-
Upload
nisa-soomro -
Category
Education
-
view
189 -
download
2
description
Transcript of Basic of PHP
Course Instructor: Nisa Soomro
PHP and MySQL Web Development Fourth Edition “Luke Welling, Laura Thomson”
http://sage.math.washington.edu/home/wstein/www/home/agc/lit/php/PHPMySQL.pdf
www.W3school.com
2
PHP Intro
PHP Install
PHP Syntax
PHP Variables
PHP Echo / Print
PHP Data Types
PHP Constants
PHP Operators
PHP If...Else...Elseif
PHP Switch
PHP While Loops
PHP For Loops
3
What is PHP?
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 costs nothing, it is free to download and use
4
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain HTML
PHP files have extension ".php"
5
<?php
echo "<h1 align='center'>Welcome to PHP </h1>";
?>
Execute this code and check the “View page source” you will find simple following code
<h1 align='center'>Welcome to PHP </h1>
6
PHP can generate dynamic page content
PHP can create, open, read, write, delete, and close files on the server
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your database
PHP can restrict users to access some pages on your website
PHP can encrypt data
With PHP you are not limited to output HTML. You can output images,PDF files, and even Flash movies. You can also output any text, such asXHTML and XML.
7
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
8
The most universally effective PHP tag style is:
<?php
// Php Code here
?>
If you use this style, you can be positive that your tags will always be correctly interpreted.
9
HTML script tags:
<script language=“php”>
// php code here
</script>
10
Short or short-open tags look like this:
<?
// Php Code here
?>
Set the short_open_tag setting in your php.ini file to on. This option must be disabled to parse XML with PHP because the same syntax is used for XML tags.
11
ASP-style tags:
ASP-style tags mimic the tags used by Active Server Pages to delineate code blocks. ASP-style tags look like this:
<%
// php code here
%>
To use ASP-style tags, you will need to set the configuration option in your php.ini file.
12
A comment in PHP code is a line that is not read/executed as part of theprogram. Its only purpose is to be read by someone who is editing thecode!
Comments are useful for:
To let others understand what you are doing - Comments let otherprogrammers understand what you were doing in each step (if you workin a group)
To remind yourself what you did - Most programmers have experiencedcoming back to their own work a year or two later and having to re-figureout what they did. Comments can remind you of what you were thinkingwhen you wrote the code
13
PHP supports two types of comments
Single line comment
// This is a single line comment# This is also a single line comment
Multiline comment
/* this is multiline comment
this is multiline comment
*/
14
In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo, etc.) are NOT case-sensitive.
In the example below, all three echo statements below are legal (and equal):
<?phpECHO "Hello World!<br>";echo "Hello World!<br>";EcHo "Hello World!<br>";
?>
15
However; in PHP, all variables are case-sensitive.
In the example below, only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are treated as three different variables):
<?php$color="red";echo "My car is " . $color . "<br>";echo "My house is " . $COLOR . "<br>";echo "My boat is " . $coLOR . "<br>";
?>
16
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:
17
$four = 2 + 2; // single spaces
$four = 2 + 2 ; // spaces and tabs
$four =
2+
2; // multiple lines
All are same. It doesn’t matter how many spaces your are providing in a statement, it will be considered as a single space.
18
Variables are "containers" for storing information
PHP variables can be used to hold values (x=5) or expressions (z=x+y).
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case sensitive ($y and $Y are two different variables)
19
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.
20
PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
<?php$txt="Hello world!";$x=5;$y=10.5;
?>
After the execution of the statements above, the variable txt will hold thevalue Hello world!, the variable x will hold the value 5, and thevariable y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes aroundthe value. 21
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.
22
In PHP there is two basic ways to get output: echo and print.
There are some differences between echo and print:
echo - can output one or more strings
print - can only output one string, and returns always 1
Tip: echo is marginally faster compared to print as echo does not return any value.
23
echo is a language construct, and can be used with or without parentheses: echo or echo().
Display Strings
The following example shows how to display different strings with the echo command (also notice that the strings can contain HTML markup):
<?phpecho "<h2>PHP is fun!</h2>";echo "Hello world!<br>";echo "I'm about to learn PHP!<br>";echo "This", " string", " was", " made", " with multiple parameters.";
?>
24
Display Variables
The following example shows how to display strings and variables with the echo command:
<?php$txt1="Learn PHP";$txt2="W3Schools.com";$cars=array("Volvo","BMW","Toyota");echo $txt1;echo "<br>";echo "Study PHP at $txt2";echo "<br>";echo "My car is a {$cars[0]}";
?>25
print is also a language construct, and can be used with or without parentheses: print or print().
Display Strings
The following example shows how to display different strings with the print command (also notice that the strings can contain HTML markup):
<?phpprint "<h2>PHP is fun!</h2>";print "Hello world!<br>";print "I'm about to learn PHP!";
?>
26
Display Variables
The following example shows how to display strings and variables with the print command:
<?php$txt1="Learn PHP";$txt2="W3Schools.com";$cars=array("Volvo","BMW","Toyota");print $txt1;print "<br>";print "Study PHP at $txt2";print "<br>";print "My car is a {$cars[0]}";
?>
27
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
28
A variable declared in a function is considered local; that is, it can bereferenced solely in that function. Any assignment outside of thatfunction will be considered to be an entirely different variable from theone contained in the function:
29
<?
$x = 4;
function assignx () {
$x = 0;
print "\$x inside function is $x. ";
}
assignx();
print "\$x outside of function is $x. ";
?>
30
In contrast to local variables, a global variable can be accessed in anypart of the program. However, in order to be modified, a global variablemust be explicitly declared to be global in the function in which it is tobe modified. This is accomplished, conveniently enough, by placing thekeyword GLOBAL in front of the variable that should be recognized asglobal. Placing this keyword in front of an already existing variable tellsPHP to use the variable having that name. Consider an example:
31
<?
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
32
The final type of variable scoping that I discuss is known as static. Incontrast to the variables declared as function parameters, which aredestroyed on the function's exit, a static variable will not lose its valuewhen the function exits and will still hold that value should the functionbe called again.
You can declare a variable to be static simply by placing the keywordSTATIC in front of the variable name.
33
<?
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print “ ";
}
keep_track();
keep_track();
keep_track();
?>
34
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";
?> 35
PHP has a total of eight data types which we use to construct our variables:
1. Integers: are whole numbers, without a decimal point, like 4195.
2. Doubles: are floating-point numbers, like 3.14159 or 49.1.
3. Booleans: have only two possible values either true or false.
4. NULL: is a special type that only has one value: NULL.
5. Strings: are sequences of characters, like 'PHP supports string operations.'
6. Arrays: are named and indexed collections of other values.
7. Objects: are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
8. Resources: are special variables that hold references to resources external to PHP (such as database connections).
The first five are simple types, and the next two (arrays and objects) are compound - the compound types canpackage up other arbitrary values of arbitrary type, whereas the simple types cannot.
36
They are whole numbers, without a decimal point, like 4195. They are the simplest type .they correspond to simple whole numbers, both positive and negative. Integers can be assigned to variables, or they can be used in expressions, like so:
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals have a leading 0x.
37
They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal places needed. For example, the code:
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print(.$many + $many_2 = $few<br>.);
It produces the following browser output:
2.28888 + 2.21112 = 4.5
38
Booleans can be either TRUE or FALSE.
$x=true;
$y=false;
Booleans are often used in conditional testing.
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
39
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this:
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed:
$my_var = null;
A variable that has been assigned NULL has the following properties:
It evaluates to FALSE in a Boolean context.
It returns FALSE when tested with IsSet() function.
40
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
<?php
$x = "Hello world!";
echo $x;
echo "<br>";
$x = 'Hello 12BS(CS)';
echo $x;
?>
41
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
42
\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 (\)
43
An array stores multiple values in one single variable.
In the following example we create an array.
<?php
$cars=array("Volvo","BMW","Toyota");
echo $car[0];
echo $car[1];
echo $car[2];
?>
44
Constants are like variables except that once they are defined they cannot be changed or undefined.
A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Note: Unlike variables, constants are automatically global across the entire script.
45
To set a constant, use the define() function - it takes three parameters:
1. The first parameter defines the name of the constant,
2. the second parameter defines the value of the constant,
3. the optional third parameter specifies whether the constant name should be case-insensitive. Default is false.
46
The example below creates a case-sensitive constant, with the value of "Welcome to W3Schools.com!":
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
The example below creates a case-insensitive constant, with the value of "Welcome to W3Schools.com!":
<?phpdefine("GREETING", "Welcome to W3Schools.com!", true);echo greeting;?>
47
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.
48
49
PHP Arithmetic Operators
50
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
<?php$x=10;$y=6;echo ($x + $y); // outputs 16echo ($x - $y); // outputs 4echo ($x * $y); // outputs 60echo ($x / $y); // outputs 1.6666666666667echo ($x % $y); // outputs 4
?>
51
The PHP assignment operators is used to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.
52
Assignment Same as... Description
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
<?php$x=10;echo $x; // outputs 10
$y=20;$y += 100;echo $y; // outputs 120
$z=50;$z -= 25;echo $z; // outputs 25
$i=5;$i *= 6;echo $i; // outputs 30
$j=10;$j /= 5;echo $j; // outputs 2
$k=15;$k %= 4;echo $k; // outputs 3?>
53
Operator Name Example Result
. Concatenation $txt1 = "Hello"$txt2 = $txt1 . " world!"
Now $txt2 contains "Hello world!"
.= Concatenation assignment
$txt1 = "Hello"$txt1 .= " world!"
Now $txt1 contains "Hello world!"
54
55
<?php$a = "Hello";$b = $a . " world!";echo $b; // outputs Hello world!
$x="Hello";$x .= " world!";echo $x; // outputs Hello world!
?>
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
56
57
<?php$x=10;echo ++$x; // outputs 11
$y=10;echo $y++; // outputs 10
$z=5;echo --$z; // outputs 4
$i=5;echo $i--; // outputs 5
?>
The PHP comparison operators are used to compare two values (number or string):
58
Operator Name Example Result
== Equal $x == $y True if $x is equal to $y
=== Identical $x === $y True if $x is equal to $y, and they are of the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
!== Not identical $x !== $y True if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y True if $x is greater than $y
< Less than $x < $y True if $x is less than $y
>= Greater than or equal to $x >= $y True if $x is greater than or equal to $y
<= Less than or equal to $x <= $y True if $x is less than or equal to $y
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
59
The PHP array operators are used to compare arrays:
60
Operator Name Example Result
+ Union $x + $y Union of $x and $y (but duplicate keys are not overwritten)
== Equality $x == $y True if $x and $y have the same key/value pairs
=== Identity $x === $y True if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non-identity $x !== $y True if $x is not identical to $y
Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
1. if statement - executes some code only if a specified condition is true
2. if...else statement - executes some code if a condition is true and another code if the condition is false
3. if...elseif....else statement - selects one of several blocks of code to be executed
4. switch statement - selects one of many blocks of code to be executed
61
The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition){code to be executed if condition is true;}
<?php$t=date("H");if ($t<"20"){echo "Have a good day!";}
?>
62
Use the if....else statement to execute some code if a condition is true and another code if the condition is false.
Syntax
if (condition){code to be executed if condition is true;}else{code to be executed if condition is false;}
63
<?php$t=date("H");if ($t<"20"){
echo "Have a good day!";}else{
echo "Have a good night!";}
?>
64
Use the if....elseif...else statement to select one of several blocks of code to be executed.
Syntax
if (condition){
code to be executed if condition is true;}
elseif (condition){
code to be executed if condition is true;}
else{
code to be executed if condition is false;}
65
<?php$t=date("H");if ($t<"10"){echo "Have a good
morning!";}
elseif ($t<"20"){echo "Have a good day!";}
else{echo "Have a good night!";}
?>
66
The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n){case label1: code to be executed if n=label1; break;case label2: code to be executed if n=label2; break;case label3: code to be executed if n=label3; break;...default: code to be executed if n is different from all labels;} 67
This is how it works: First we have a single expression n (most often avariable), that is evaluated once. The value of the expression is thencompared with the values for each case in the structure. If there is amatch, the block of code associated with that case is executed.Use break to prevent the code from running into the next caseautomatically. The default statement is used if no match is found.
68
<?php
$d=date("D");
switch ($d)
{
case "Mon": echo "Today is Monday"; break;
case "Tue": echo "Today is Tuesday"; break;
case "Wed": echo "Today is Wednesday"; break;
case "Thu": echo "Today is Thursday"; break;
case "Fri": echo "Today is Friday"; break;
case "Sat": echo "Today is Saturday"; break;
case "Sun": echo "Today is Sunday"; break;
default: echo "Wonder which day is this ?";
}
?> 69
Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
1.while - loops through a block of code as long as the specified condition is true
2.do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
3.for - loops through a block of code a specified number of times
4.foreach - loops through a block of code for each element in an array
70
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true){code to be executed;}
71
The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run as long as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):
Example
<?php$x=1;while($x<=5){echo "The number is: $x <br>";$x++;}
?>
72
The do...while loop will always execute the block of code once, it willthen check the condition, and repeat the loop while the specifiedcondition is true.
Syntax
do{code to be executed;}
while (condition is true);
73
The example below first sets a variable $x to 1 ($x=1;). Then, the do whileloop will write some output, and then increment the variable $x with 1. Thenthe condition is checked (is $x less than, or equal to 5?), and the loop willcontinue to run as long as $x is less than, or equal to 5:
Example
<?php$x=1;do{echo "The number is: $x <br>";$x++;}
while ($x<=5)?>
74
Notice that in a do while loop the condition is tested AFTER executing the statements within the loop. This means that the do while loop would execute its statements at least once, even if the condition fails the first time.
The example below sets the $x variable to 6, then it runs the loop, and then the condition is checked:
<?php$x=6;do
{echo "The number is: $x <br>";$x++;}
while ($x<=5)?>
75
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter){code to be executed;}
76
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
77
The example below displays the numbers from 0 to 10:
Example
<?phpfor ($x=0; $x<=10; $x++){echo "The number is: $x <br>";}
?>
78
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
Syntax
foreach ($array as $value){code to be executed;}
For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
79
The following example demonstrates a loop that will output the values of the given array ($colors):
Example
<?php$colors = array("red","green","blue","yellow");foreach ($colors as $value){
echo "$value <br>";}
?>
80
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.
81
In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
82
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.
83
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.
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
84
The real power of PHP comes from its functions; it has more than 1000 built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
85
A user defined function declaration starts with the word "function":
Syntax
function functionName(){code to be executed;}
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!
86
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call the function, just write its name:
<?phpfunction writeMsg(){echo "Hello world!";}
writeMsg(); // call the function?>
87
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just seperate them with a comma.
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
88
A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
89
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
90
<?php
function table($a = 12)
{
for($i=1; $i<10; $i++)
{
echo " $a * $i = $a*$i <br />" ;
}
}
table();
table(3);
?>
91
It is possible to pass arguments to functions by reference. This meansthat a reference to the variable is manipulated by the function ratherthan a copy of the variable's value.
Any changes made to an argument in these cases will change thevalue of the original variable. You can pass an argument by referenceby adding an ampersand (&) to the variable name in either the functioncall or the function definition.
92
<?php
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive($orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
93
What is an Array?
An array stores multiple values in one single variable:
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1="Volvo";$cars2="BMW";$cars3="Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
94
An array can hold many values under a single name, and you can access the values by referring to an index number.
Create an Array in PHP
In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:
1.Indexed arrays - Arrays with numeric index
2.Associative arrays - Arrays with named keys
3.Multidimensional arrays - Arrays containing one or more arrays
95
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0):
$cars=array("Volvo","BMW","Toyota");
or the index can be assigned manually:
$cars[0]="Volvo";$cars[1]="BMW";$cars[2]="Toyota";
96
The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:
Example
<?php$cars=array("Volvo","BMW","Toyota");echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";?>
97
The count() function is used to return the length (the number of elements) of an array:
Example
<?php$cars=array("Volvo","BMW","Toyota");echo count($cars);?>
98
To loop through and print all the values of an indexed array, you could use a for loop, like this:
Example
<?php$cars=array("Volvo","BMW","Toyota");$arrlength=count($cars);
for($x=0; $x<$arrlength; $x++){echo $cars[$x];echo "<br>";}
?> 99
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
$age['Peter']="35";$age['Ben']="37";$age['Joe']="43";
The named keys can then be used in a script:
Example
<?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");echo "Peter is " . $age['Peter'] . " years old.";?>
100
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
Example
<?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value){echo "Key=" . $x . ", Value=" . $x_value;echo "<br>";}
?>
101
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.
102
$marks = array(
"mohammad" => array
(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
" Zara" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
) );
103
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
104
http://www.w3schools.com/php/
http://www.tutorialspoint.com/php/php_introduction.htm
105