Nothing Special   »   [go: up one dir, main page]

PHP 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 78

Chapter 5

PHP
Introduction
 HTML- focuses on marking up information(define
the content of web pages)
 CSS- focuses on formatting and presenting
information(specify the layout of web pages)
 JavaScript to program the behavior of web pages( to add
dynamic features on the client side)
 PHP is a server scripting language, and a powerful tool
for making dynamic and interactive Web pages. ( used
to add dynamic features on the server side…including
database interaction)
Cont..
 Static VS Dynamic Web Sites
• Static Websites-Written in HTML only
• Dynamic Websites – do more interactive things.
• Markup language like HTML
• Scripting (both client and server side) language
• Style sheet (for presentation) like CSS
 Client-Side Scripting VS Server-Side Scripting
 Client-Side
 Server-Side
• PHP is a server scripting language, and a powerful
tool for making dynamic and interactive Web
pages.
Client side scripting vs. server side scripting

Client side Server side


Webserver

HTML* PHP engine

HTML PHP
Common Web Application Architecture

Requests
Browser Server

Responses

Requests
Responses
Responses
Script
Database Engine
Requests

5
Client-side Technologies
CLIENT
Server
SIDE

Browser

HTML
JavaScript
CSS

Script
Database Engine

6
Server-Side
Browser Server

Apache

SERVER SIDE

Database Script PHP


MySQL Engine

7
Client side vs Server side scripting
Client-side Server-side
Scripts are stored on the client (engine Scripts are stored on the server
is in browser) (engine is on server)
Scripts can be modified by the end Scripts cannot be modified by the end
user user
Browser-dependent Browser-independent
Source code can be viewed Source code can’t be viewed
Can’t communicate with a database Can communicate with a database

No network overhead Dependent on network bandwidth

Processing is done by the browser - Processing is done by the server -


fast slower
How web server works?
 Client specifies document at a specific web address.
E.g. http://www.bdu.edu.et/
 If the requested document is HTML or text, the server
simply forwards it back to the client.
 However, the requested document may be an
executable script, or it may be HTML with an embedded
script, In this cases, the server executes the script
 If the entire document was a script, the server simply
sends the output back to the client
 If the document had an embedded script, the script
sections are replaced with the output and the modified
document is then sent to the client
Note that the client never sees the server-side
script code
What is PHP?
• PHP is a scripting language, created in 1994 by Rasmus
Lerdorf from the Apache Group, that is designed for
producing dynamic Web content.
• PHP stands for PHP: Hypertext Preprocessor
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is a scripting language designed specifically for use on
the web.
• It has features to aid you in programming the tasks needed
to develop dynamic web applications.
• Its similarity to C’s syntax and open-source nature make PHP
relatively easy to learn.
Cont…
• PHP is another HUGE language
It is a fully functional language
It has an incredible amount of built-in features
• Form processing
• Output / generate various types of data (not just
text)
• Database access
 Allows for various DBs and DB formats
• Object-oriented features
 Somewhat of a loose hybrid of C++ and Java

11
Cont..
• Interpreted rather than compiled like Java or C.
• an embedded scripting language, meaning that it can
exist within HTML code.
• a server-side technology, everything happens on the
server as opposed to the Web browser’s computer, the
client.
• cross-platform, meaning it can be used on Linux,
Windows, Macintosh, etc., making PHP very portable.
• compatible with almost all servers used today (Apache,
IIS, etc.)
• easy to learn and runs efficiently on the server side
12
What is a PHP File?

• PHP files can contain text, HTML, JavaScript


code, and PHP code
• PHP code are executed on the server, and the
result is returned to the browser as plain HTML
• PHP files have a default file extension of “.php"
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, 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
Why PHP?
• Powerful and flexible,
• PHP is easy to learn and runs efficiently on the server
side
• PHP runs on different platforms (Windows, Linux, Unix,
Mac OS X, etc.)
• PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
• PHP has support for a wide range of databases(MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL, Generic
ODBC, etc)
• PHP is an open source software and free to download
and use.
• Cheap
• Easy to set up
Basic PHP Syntax
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
• <?php tag informs the server that PHP code is to
follow.
• The server then switches over to PHP mode in
anticipation of a PHP command.
• The ?> tag closes out the PHP mode with the server
resuming its scanning in HTML mode once more.
Cont..
• All PHP code is contained in one of several script
tags:
1. <?php
// Some code here
?>

2. <?
// Some code
?>

3. <script language=“PHP">
// Some code here
</script>
• When a PHP file is requested, the PHP interpreter
parses the entire file
• Any content within PHP delimiter tags is interpreted,
and the output substituted
• Any other content (i.e. not within PHP delimiter tags) is
simply passed on unchanged
• This allows us to easily mix PHP and other content (ex:
HTML)
• Each code line in PHP must end with a semicolon.
• The semicolon is a separator which is used to
distinguish one set of instructions from another.
• With PHP, there are two basic statements to output
text in the browser: echo and print.
Example
HTML 5 Document
<!DOCTYPE html>
<html> Root HTML Tag
<head>
<title>Simple PHP Example</title>
Document Head
</head>
<body>
<?php echo "<p><h1>Output</h1>";
D echo "<h2>Output</h2>";
O echo "<h3>Output</h3></p>";
C PHP Code
?>
<script language="PHP">
B echo "\n<b>More PHP Output</b>\n";
O echo "New line in source but not rendered";
D
echo "<br/>";
Y
echo "New line rendered but not in source";
</script>
</body>
</html>
Example
<html>
<head><title>Hello World in PHP</title></head>
<body>
<?php //this is a comment in PHP, yes just like in Java
// <?php indicates the start of PHP directives in HTML
echo "Hello World, $_ENV["USER"];
// our Hello World with your username
//Finally terminate the PHP directives
?>
</body>
</html>
The use of include() fuction
• Used to include external PHP file into another PHP code
Example
setdate.php:
<?php $today=getdate(time());?>
footer.php:
<SMALL>Today is <?php print $today[weekday];?></SMALL>
Index.php:

<?php
include ("setdate.php");
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
print "World Peace Declared";
?>
</P><HR>
<?php include ("footer.php");
?>
Script execution
• There are two methods for executing PHP scripts:
 via the Web server, and
 the command-line interface (CLI).
• The first method will be used almost exclusively in
this course, so you may ignore the CLI for now.
1. Upload your .php file to your Web account (i.e.,
within the www-home directory).
2. Make sure the permissions are set correctly;
3. Navigate to the file with a Web browser.

22
Cont...
• The PHP processor has two modes: copy (HTML) and
interpret (PHP).
• PHP processor takes a PHP document as input and
produces an HTML document file
• When it finds HTML code in the input file, simply
copies it to the output file
• When it finds PHP script, it interprets it and send any
output of the script to the output file
• This new output file is sent to the requesting browser.
• The client never sees the PHP script.

23
Basic PHP Facts
• Like JS, PHP is usually purely interpreted
• Syntax and semantics are closely related to JS
• Like JS, PHP uses dynamic typing
• PHP variables are case sensitive, but reserved words
and function names are not.
E.g
• while, WHILE, While, and wHiLe are same

24
25
Comments in PHP
• In PHP, three different kinds (Java and Perl)
(a) // ... ; for single line
(b) # ... ; for single line
(c) /* ... */ ; for multiple-line
<html>
<body>
<?php
//This is a comment
# this is also a comment
/*
This is a comment
block
*/
?></body>
</html>
PHP Variables
• A variable is a holder for a type of data.
• They are dynamically typed, so you do not need to
specify the type (e.g., int, float, etc.).
• All variables in PHP start with a $ sign symbol.
<?php
$txt="Hello World!";
$x=16;
?>
• In PHP, a variable does not need to be declared
before adding a value to it.
• PHP is a Loosely Typed Language
Rules for PHP variable
• A variable starts with the $ sign, followed by
the name of the variable
• A variable name must begin with a letter or
the underscore character
• A variable name can only contain alpha-
numeric characters and underscores (A-z, 0-9,
and _ )
• A variable name should not contain spaces
• Variable names are case sensitive ($y and $Y
are two different variables)
Example
<!DOCTYPE html>
<html>
<body>
<?php
$txt = “Php variable example!";
$x = 30;
$y = 20.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
Environment/predefined Variables
• Beyond the variables you declare in your code, PHP has
a collection of environment variables, which are system
defined variables that are accessible from anywhere
inside the PHP code ("superglobals“ variables),
• These variables allow the script access to server
information, form parameters, environment
information, etc
• All of these environment variables are stored by PHP as
arrays.
• Some you can address directly by using the name of the
index position as a variable name. Other can only be
accessed through their arrays.
30
Some of the environment variables include:

• $_SERVER
 Contains information about the server and the
HTTP connection. Analogous to the old
$HTTP_SERVER_VARS array (which is still
available, but deprecated).
• $_COOKIE
 Contains any cookie data sent back to the server
from the client. Indexed by cookie name.
Analogous to the old $HTTP_COOKIE_VARS
array (which is still available, but deprecated).

31
Cont....
• $_GET
 Contains any information sent to the server as a search string
as part of the URL. Analogous to the old $HTTP_GET_VARS
array (which is still available, but deprecated).
• $_POST
 Contains any information sent to the server as a POST style
posting from a client form. Analogous to the old
$HTTP_POST_VARS array (which is still available, but
deprecated).
• $_FILE
 Contains information about any uploaded files. Analogous to
the old $HTTP_POST_FILES array (which is still available, but
deprecated).
• $_ENV
 Contains information about environmental variables on the
server. Analogous to the old $HTTP_ENV_VARS array (which is
still available, but deprecated). 32
PHP Variable Scopes
• PHP has four different variable scopes:
 local
 global
 static
Local scope
• A variable declared within a PHP function is local
and can only be accessed within that function:
<?php
$x=5; // global scope
function myTest()
{
$x=6; // local scope
echo $x; // local scope
}
myTest();
?>
• Local variables are deleted as soon as the function
is completed
Global scope
• A variable declared outside a function has a GLOBAL
SCOPE and can only be accessed outside a function:
• The global keyword is used to access a global variable from
within a function(use the global keyword before the
variables (inside the function))
<?php
$x=5; // global scope
$y=10; // global scope
function myTest(){
global $x,$y;
$y=$x+$y; }
myTest();
echo $y; // outputs 15
?>
• PHP also stores all global variables in an array called
$GLOBALS[index].
• The index holds the name of the variable.
• This array is also accessible from within functions and can
be used to update global variables directly.
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
Static scope
• When a function is completed/executed, all of its variables
are normally deleted. However, sometimes you want a
local variable to not be deleted for future use.
• To do this, use the static keyword when you first declare
the variable:
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest(); // 0
myTest(); // 1
myTest(); // 2
?>
PHP Data Types
• Variables can store data of different types,
and different data types can do different
things.
• PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
38
Fundamental variable types
• Numeric
 integer. Integers (±2 raised 31); values outside this
range are converted to floating-point.
 float. Floating-point numbers.
• Boolean: true or false; PHP internally resolves these
to 1 (one) and 0 (zero) respectively.
• string: String of characters.
• array: An array stores multiple values in one single
variable.(an array of values, possibly other arrays )
• object :an object is a data type which stores data and
information on how to process that data. In PHP, an
object must be explicitly declared.
39
Cont…
• Resource:
• A handle to something that is not PHP data (e.g., image
data, database query result).
• Or in other words, Resource is to represent a PHP
extension resource (e.g. Database query, open file,
database connection, etc). You will never directly touch
this type, it will be passed to the relevant functions that
know how to interact with the specified resource.
• Null :
• data type with only one possible value: null. Marks
variables as being empty. Works with the isset()
operator; will return ‘false’ for null. Example:
$var=NULL;
40
Cont....
• PHP has a useful function named var_dump()
that prints the current type and value for one
or more variables.
• Arrays and objects are printed recursively with
their values indented to show structure.
$a = 35;
Output of the code
$b = "Programming is fun!"; int(35)
string(19) "Programming is
$c = array(1, 1, 2, 3); fun!"
var_dump($a,$b,$c); array(4) {
[0]=> int(1)
[1]=>int(1)
[2]=>int(2)
[3]=>int(3)
41
PHP Strings
• A string is a sequence of characters, like "Hello
world!".
• A string can be any text inside quotes. You can use
single or double
'I am a string in single quotes'
"I am a string in double quotes"
• The PHP parser determines strings by finding matching
quote pairs. So, all strings must start and finish with
the same type of quote - single or double.
• Only one type of quote mark is important when
defining any string, single (') or double (").
$string_1 = "This is a string in double quotes";
42

$string_0 = ‘’ // a string with zero characters


• Singly quoted strings are treated almost literally,
whereas doubly quoted strings replace variables
with their values as well as specially interpreting
certain character sequences.
• Strings that are delimited by double quotes (as in
"this") are preprocessed in both the following
two ways by PHP:
• Certain character sequences beginning with
backslash (\) are replaced with special characters
• Variable names (starting with $) are replaced with
string representations of their values.
String Concatenation Operator

• To concatenate two string variables together,


use the dot (.) operator:
E.g
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 ." " .$txt2;
?>
Output
Hello World! What a nice day!
The strlen()function
• The strlen() function is used to find the length of
a string.
E.G
<?php
echo strlen("Hello world!");
?>
Output
12
• The length of a string is often used in loops or
other functions, when it is important to know
when the string ends.
The strpos()function
• The strpos() function is used to search for a string or
character within a string. (first position in the string is
0, and not 1.)
• If a match is found in the string, this function will
return the position of the first match. If no match is
found, it will return FALSE.
E.g
<?php
echo strpos("Hello world!","world"); // output=6
?>
The str_word_count() function
• The PHP str_word_count() function counts the number of
words in a string:
E.g
<?php
echo str_word_count("Hello world!"); //output =2
?>
Reverse a String
• The PHP strrev() function reverses a string:
E.g <?php
echo strrev("Hello world!"); //output=!dlrow olleH
?>
The str_replace() function
• The PHP str_replace() function replaces some
characters with some other characters in a string.
<?php
echo str_replace("world", “PHP", "Hello world!");
?> Output: Hello PHP!
• The example below replaces the text "world"
with “PHP":
• The PHP string functions are part of the PHP core.
No installation is required to use these functions.
• Refer this page for full string functions
http://www.w3schools.com/php/php_ref_string.
asp
PHP Constants
• 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.
• Syntax
define(name, value, case-insensitive)
// name: Specifies the name of the constant // value: Specifies
the value of the constant //case-insensitive: Specifies whether
the constant name should be case-insensitive. Default is false
• E. g
<?php
// case-sensitive constant name
define("GREETING", "Welcome to Bahir Dar University!");
echo GREETING;
?>
PHP Operators
• Operators are used to perform operations on
variables and values.
• PHP divides the operators in the following
groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
PHP Arithmetic Operators
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

** Exponentiation $x ** $y Result of raising $x to the $y'th power


(Introduced in PHP 5.6)
PHP Assignment Operators
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 Comparison Operators
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same
type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the
same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y


equal to

<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
PHP Increment / Decrement Operators
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
PHP Logical Operators
Operato Name Example Result
r
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


PHP String Operators

Operator Name Example Result

. Concatenati $txt1 . $txt2 Concatenation of


on $txt1 and $txt2

.= Concatenati $txt1 .= $txt2 Appends $txt2 to


on $txt1
assignment
PHP Array Operators
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have
the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have
the same key/value pairs in
the same order and of the
same types
!= Inequality $x != $y Returns true if $x is not equal
to $y
<> Inequality $x <> $y Returns true if $x is not equal
to $y
!== Non-identity $x !== $y Returns true if $x is not
identical to $y
PHP Conditional Statements
• Conditional statements are used to perform different
actions based on different conditions
• In PHP we have the following conditional statements:
• if statement - executes some code only if a specified
condition is true
• if...else statement - executes some code if a condition
is true and another code if the condition is false
• if...elseif....else statement - specifies a new condition
to test, if the first condition is false
• switch statement - selects one of many blocks of code
to be executed
PHP - The if Statement
• 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;
}
• Example
<?php
$t = date("H"); //24 hours format of an hour
if ($t < “15") {
echo "Have a good day!";
}
?>
PHP - 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
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The if...elseif....else Statement
• 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;
}
Example
<?php
$d=date("D"); // A textual representation of a day (three letters)
if($d=="Fri")
echo "Have a nice weekend!";
Else if($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
PHP switch statement
Example

<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
?>
PHP looping statements
PHP Looping - While Loops
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
PHP Looping - For Loops
E.g
<!DOCTYPE html>
<html>
<body>

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
Cont..
• 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.
E.g.
<?php
$x=array("one","two","three");
foreach($x as $value)
{
echo $value . "<br />";
}
?>
PHP Functions
• A function is a self-contained block of code that
can be called by your script.
• When called (or invoked), the function’s code is
executed and performs a particular task.
• In PHP, functions come in two flavors – those built
in to the language(e.g strtoupper()), and those that
you define yourself.
• Naming conventions for functions are the same as
for normal variables in PHP.
• Note: variables names are case sensitive in PHP,
function names are not!)
Example
<?php
Function writeName(){
echo “sam abebe";
}
echo "My name is "; writeName();
?>
Adding parameters
<?php
Function writeName($fname){
echo $fname. " abebe”.<br />";
}
echo "My name is ";
writeName(“sam");
echo "My sister's name is ";
writeName(“Helen");
?>
PHP Functions - Return values

<?php
function add($x,$y)
{
$total=$x+$y;
Return $total;
}
echo "1 + 16 = " . add(1,16);
?>
PHP Arrays
• An array is a data structure that stores one or more
similar type of values in a single value.
• In PHP, there are three types of arrays:
 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 arrays- Arrays containing one or
more arrays
Numeric Array
• A numeric array stores each array element with a
numeric index.
E.g
<html><body>
<?php
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br/>";
}
?>
</body>
</html>
Associative array
• 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.
<?php
$salary= array(“abel"=>3200, “Sam"=>3000, “bet"=>3400);
echo "Salary of Abel is ". $salary[‘abel'] . "<br />";
echo "Salary of bet is ". $salary[‘bet'] . "<br />";
echo "Salary of sam is ". $salary[‘sam'] . "<br />";
?>
Multidimensional array
• 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.
• Values in the multi-dimensional array are accessed
using multiple index.
$families = array
(
"Griffin"=>array ("Peter","Lois","Megan"),
"Quagmire"=>array ("Glenn"),
"Brown"=>array("Cleveland","Loretta","Junior")
);
echo "Is " . $families['Griffin'][2] . " a part of the Griffin
family?";
<html><body>
<?php /*Accessing multi-dimensional
array values */
$marks = array(
echo "Marks for abel in physics : " ;
"abel" => array( echo $marks['abel']['physics'] . "<br
"physics" => 35, />";
"maths" => 30, echo "Marks for sam in maths : ";
"chemistry" => 39 ), echo $marks['sam']['maths'] . "<br
/>";
"sam" => array( echo "Marks for sam in chemistry :
"physics" => 30, ";
"maths" => 32, echo $marks['sam']['chemistry'] .
"chemistry" => 29 ), "<br />";
?> </body></html>
"beti" => array
(
"physics" => 31,
"maths" => 22,
73
"chemistry" => 39) );
Mixing array types
 We can even mix the two if we'd like
 PHP arrays are a cross between numbered arrays and
associative arrays.
In the example below, three literal arrays are declared as follows:
1. A numerically indexed array with indices running from 0 to 4.
2. An associative array with string indices.
3. A numerically indexed array, with indices running from 5 to 7.
<?php
$array1 = array(2, 3, 5, 7, 11);
$array2 = array("one" => 1,
"two" => 2,
"three" => 3);
$array3 = array(5 => "five", "six", "seven");
Print ($array1[3], $array2["one"], $array3[6]);
?>
Get The Length of an Array
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Example
<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
{
echo $numbers[$x];
echo "<br>";
}
?>
Loop Through an Associative Array

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"4
3");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x. ", Value=" . $x_value;
echo "<br>";
}
?>
PHP - Sort Functions For Arrays
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order,
• according to the value
• ksort() - sort associative arrays in ascending order,
• according to the key
• arsort() - sort associative arrays in descending
order, according to the value
• krsort() - sort associative arrays in descending
order, according to the key

You might also like