Unit - I History of PHP: Released
Unit - I History of PHP: Released
INTRODUCTION
HISTORY OF PHP
PHP as it's known today is actually the successor to a product named PHP/FI. Created in 1994 by
Rasmus Lerdorf, the very first incarnation of PHP was a simple set of Common Gateway Interface (CGI)
binaries written in the C programming language. Originally used for tracking visits to his online resume,
he named the suite of scripts "Personal Home Page Tools," more frequently referenced as "PHP Tools."
Over time, more functionality was desired, and Rasmus rewrote PHP Tools, producing a much larger and
richer implementation. This new model was capable of database interaction and more, providing a
framework. In June of 1995, Rasmus released the source code for PHP Tools to the public, which
allowed developers to use it as they saw fit. This also permitted - and encouraged - users to provide
fixes for bugs in the code, and to generally improve upon it.
In September of that year, Rasmus expanded upon PHP and - for a short time - actually dropped
the PHP name. Now referring to the tools as FI (short for "Forms Interpreter"), the new implementation
included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic
interpretation of form variables, and HTML embedded syntax. The syntax itself was similar to that of
Perl, albeit much more limited, simple, and somewhat inconsistent. In fact, to embed the code into an
HTML file, developers had to use HTML comments. Though this method was not entirely well-received,
FI continued to enjoy growth and acceptance as a CGI tool --- but still not quite as a language. However,
this began to change the following month; in October, 1995, Rasmus released a complete rewrite of the
code. Bringing back the PHP name, it was now (briefly) named "Personal Home Page Construction Kit,"
and was the first release to boast what was, at the time, considered an advanced scripting interface. The
language was deliberately designed to resemble C in structure, making it an easy adoption for
developers familiar with C, Perl, and similar languages. Having been thus far limited to UNIX and POSIX-
compliant systems, the potential for a Windows NT implementation was being explored.
The code got another complete makeover, and in April of 1996, combining the names of past
releases, Rasmus introduced PHP/FI. This second-generation implementation began to truly evolve PHP
from a suite of tools into a programming language in its own right. It included built-in support for DBM,
mSQL, and Postgres95 databases, cookies, user-defined function support, and much more. That June,
PHP/FI was given a version 2.0 status. An interesting fact about this, however, is that there was only one
single full version of PHP 2.0. When it finally graduated from beta status in November, 1997, the
underlying parsing engine was already being entirely rewritten.
Though it lived a short development life, it continued to enjoy a growing popularity in still-young
world of web development. In 1997 and 1998, PHP/FI had a cult of several thousand users around the
world. A Netcraft survey as of May, 1998, indicated that nearly 60,000 domains reported having headers
containing "PHP", indicating that the host server did indeed have it installed. This number equated to
approximately 1% of all domains on the Internet at the time. Despite these impressive figures, the
maturation of PHP/FI was doomed to limitations; while there were several minor contributors, it was
still primarily developed by an individual.
What is PHP
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create
dynamic content that interacts with databases. PHP is basically used for developing web based software
applications. PHP scripts are executed on the server.
It is powerful enough to be at the core of the biggest blogging system on the web.
It is deep enough to run the largest social network .
It is also easy enough to be a beginner's first server side language
PHP File
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"
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 as XHTML and XML.
Common uses of PHP
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and
close them.
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send
data, return data to the user.
You add, delete, modify elements within your database thru PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Characteristics of PHP
Simplicity
Efficiency
Security
Flexibility
Familiarity
Example code
"Hello World" Script in PHP
To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an essential example,
first we will create a friendly little "Hello, World!" script.
As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal HTML (or
XHTML if you're cutting-edge) you'll have PHP statements like this
<html>
<head>
<title>Hello World</title>
</head>
<body>
</body>
</html>
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource(advanced and used for database purpose)
PHP String
A string can be any text inside quotes. You can use single or double quotes:
Exampe :
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
The output is
Hello world!
Hello world!
They are sequences of characters, like "PHP supports string operations". Following are valid examples
of string
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with
their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!';
print($literally);
print "<br>";
$literally = "My $variable will print!";
print($literally);
?>
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.
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:
Example :
<?php
$x = 5985;
var_dump($x);
?>
The output is
int(5985)
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type and
value:
Example :
<?php
$x = 10.365;
var_dump($x);
?>
The output is
float(10.365)
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.
They have only two possible values either true or false. PHP provides a couple of constants especially
for use as Booleans: TRUE and FALSE, which can be used like so
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
PHP Array
In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
The output is
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
PHP Object
An object is a data type which stores data and information on how to process that data.
First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods:
Example :
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
The output is
VW
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
The output is
NULL
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions
and resources external to PHP.
VARIABLES
What is a variable
The main way to store information in the middle of a PHP program is by using a variable. Variables are
"containers" for storing information.
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.
You will create two main types of variables in your PHP code: scalar and array. Scalar variables contain
only one value at a time, and arrays contain a list of values, or even another array.
When you assign a value to a variable, you usually assign a value of one of the following types:
Integers. Whole numbers (numbers without decimals). Examples are 1, 345, and 9922786. You
can also use octal and hexadecimal notation: the octal 0123 is decimal 83 and the hexadecimal
0x12 is decimal 18.
Floating-point numbers ("floats" or "doubles"). Numbers with decimals. Examples are 1.5,
87.3446, and 0.88889992.
Strings. Text and/or numeric information, specified within double quotes (" ") or single quotes ('
').
Variables can be local or global, the difference having to do with their definition and use by the
programmer, and where they appear in the context of the scripts you are creating.
When you write PHP scripts that use variables, those variables can be used only by the script in which
they live. Scripts cannot magically reach inside other scripts and use the variables created and defined
there—unless you say they can and you purposely link them together. When you do just that, such as
when you create your own functions (blocks of reusable code that perform a particular task), you will
define the shared variables as global. That is, you will define them as able to be accessed by other scripts
and functions, as needed.
You can learn about creating your own functions, and using global as well as local variables. For now,
just understand that there are two variable scopes—local and global—that come into play as you write
more advanced scripts.
Pre-Defined Variables
In all PHP scripts, a set of pre-defined variables is available to you. You might have seen some of these
variables in the output of the phpinfo() function, if you scrolled and read through the entire results
page. Some of these pre-defined variables are called superglobals, meaning that they are always present
and available to all of your scripts.
Flow-Control Statements
PHP supports a number of traditional programming constructs for controlling the flow of execution of a
program.
Conditional statements, such as if/else and switch, allow a program to execute different pieces of code,
or none at all, depending on some condition. Loops, such as while and for, support the repeated
execution of particular code.
1. IF
The if statement checks the truthfulness of an expression and, if the expression is true, evaluates a
statement. An if statement looks like:
if (expression)
statement
To specify an alternative statement to execute when the expression is false, use the else keyword:
if (expression)
statement
else
statement
For example:
if ($user_validated)
echo "Welcome!";
else
echo "Access Forbidden!";
(or)
1.(a) - The if Statement
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
The Output is
The if....else statement executes some code if a condition is true and another code if that
condition is false.
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:
<?php
$t = date("H");
The output is
Have a good day!
2. The Switch Statement
If you want to select one of many blocks of code to be executed, use the Switch statement.
Syntax is
switch (expression){
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
Example
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 lable matches then statement will execute any specified default
code.
<html>
<body>
<?php
$d = date("D");
switch ($d){
case "Mon":
break;
case "Tue":
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
break;
case "Fri":
break;
case "Sat":
break;
case "Sun":
break;
default:
?>
</body>
</html>
The output is
Today is Wednesday
LOOPS
Loops in PHP are used to execute the same block of code a specified number of times. PHP supports
following four loop types.
while − loops through a block of code if and as long as a specified condition is true.
do...while − loops through a block of code once, and then repeats the loop as long as a special
condition is true.
3. While
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
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.
<html>
<body>
<?php
$i = 0;
$num = 50;
</body>
</html>
The output is
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
The following example makes five iterations and changes the assigned value of two variables on each
pass of the loop
<html>
<body>
<?php
$a = 0;
$b = 0;
</body>
</html>
The output is
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.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
</body>
</html>
The output is
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
OPERATORS
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
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators
There are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 20 then –
Comparison Operators
There are following comparison operators supported by PHP language. Assume variable A holds 10 and
variable B holds 20 ,
Then we have
Logical Operators
There are following logical operators supported by PHP language. Assume variable A holds 10 and
variable B holds 20 , we have
Assignment Operators
There are following assignment operators supported by PHP language −
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 −
Examples
Operators Categories
All the operators we have discussed above can be categorized into following categories −
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.
PHP has two operators that are specially designed for strings.
<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>
</body>
</html>
The output is
Hello world!
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
The lexical structure of a programming language is the set of basic rules that governs how you write
programs in that language. It is the lowest-level syntax of the language and specifies such things as what
variable names look like, what characters are used for comments, and how program statements are
separated from each other. Computer languages, like human languages, have a lexical structure. A
source code of a PHP script consists of tokens. Tokens are atomic code elements. In PHP language, we
have comments, variables, literals, operators, delimiters, and keywords.
Case Sensitivity
The names of user-defined classes and functions, as well as built-in constructs and keywords such as
echo, while, class, etc., are case-insensitive. Thus, these three lines are equivalent:
echo("hello, world");
ECHO("hello, world");
EcHo("hello, world");
Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and$NaME are three different variables.
A statement is a collection of PHP code that does something. It can be as simple as a variable assignment or as
complicated as a loop with multiple exit points. Here is a small sample of PHP statements, including function calls,
assignment, and an if statement:
PHP uses semicolons to separate simple statements. A compound statement that uses curly braces to mark a block of
code, such as a conditional test or loop, does not need a semicolon after a closing brace. Unlike in other languages,
in PHP the semicolon before the closing brace is not optional:
if ($needed) {
echo "We must have it!"; // semicolon required ...
White space
White space in PHP is used to separate tokens in PHP source file. It is used to improve the readability of
the source code.
public $isRunning;
White spaces are required in some places; for example between the access specifier and the variable
name. In other places, it is forbidden. It cannot be present in variable identifiers.
$a=1;
$b = 2;
$c = 3;
The amount of space put between tokens is irrelevant for the PHP interpreter. It is based on the
preferences and the style of a programmer.
$a = 1;
$b = 2; $c = 3;
$d
=
4;
We can put two statements into one line. Or one statement into three lines. However, source code
should be readable for humans. There are accepted standards of how to lay out your source code.
Semicolon
$a = 34;
$b = $a * 34 - 34;
echo $a;
Here we have three different PHP statements. The first is an assignment. It puts a value into
the $avariable. The second one is an expression. The expression is evaluated and the output is given to
the$b variable. The third one is a command. It prints the $a variable.
Variables
A variable is an identifier, which holds a value. In programming we say that we assign a value to a
variable. Technically speaking, a variable is a reference to a computer memory, where the value is
stored. In PHP language, a variable can hold a string, a number, or various objects like a function or a
class. Variables can be assigned different values over time.
Variables in PHP consist of the $ character, called a sigil, and a label. A label can be created from
alphanumeric characters and an underscore _ character. A variable cannot begin with a number. The
PHP interpreter can then distinguish between a number and a variable more easily.
$Value
$value2
$company_name
$12Val
$exx$
$first-name
Keywords
A keyword is a reserved word in the PHP programming language. Keywords are used to perform a specific
task in a computer program; for example, print a value, do repetitive tasks, or perform logical operations.
A programmer cannot use a keyword as an ordinary variable.
Operators
+ - * / % ++ --
= += -= *= /= .= %=
== != >< > < >= <=
&& || ! xor or
& ^ | ~ . << >>
Delimiters
A delimiter is a sequence of one or more characters used to specify the boundary between separate,
independent regions in plain text or other data stream.
$a = "PHP";
$b = 'Java';
The single and double characters are used to mark the beginning and the end of a string.
$a = array(1, 2, 3);
echo $a[1];
Constants
A constant is an identifier for a value which cannot change during the execution of the script. By
convention, constant identifiers are always uppercase.
<?php
define("SIZE", 300);
define("EDGE", 100);
#SIZE = 100;
echo SIZE;
echo EDGE;
echo "\n";
?>
define("SIZE", 300);
define("EDGE", 100);
Constants differ from variables; we cannot assign a different value to an existing constant. Constants do
not use the dollar sign character.
INSTALLATION PROCEDURE OF PHP
If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server will automatically
parse them for you.
You already have seen many functions like fopen() and fread()etc. They are built-in functions but PHP
gives you option to create your own functions as well.
What is a function?
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.
Syntax
function functionName() {
code to be executed;
}
A function name can start with a letter or underscore (not a number). Function names are not case sensitive.
Example :
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:
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
The output is :
Hello world!
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 separate them with a comma.
PHP gives you option to pass your parameters inside a function. You can pass as many as parameters
your like. These parameters work like variables inside your function. Following example takes two
integer parameters and add them together and then print them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
The output is
Sum of the two numbers is : 30
It is possible to pass arguments to functions by reference. This means that a reference to the variable is
manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable. You can
pass an argument by reference by adding an ampersand to the variable name in either the function call
or the function definition.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
The output is :
Original value is 10
Original value is 16
PHP Functions returning value
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.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
</body>
</html>
The output is
Returned value from the function : 30
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument: Consider the following example,
<!DOCTYPE html>
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
The output is
The height is : 350
The height is : 50
The height is : 135
The height is : 80
STRINGS
A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all.
The simplest way to create a string is to enclose the string literal (i.e. string characters) in single
quotation marks ('), like this:
You can also use double quotation marks ("). However, single and double quotation marks work in
different ways. Strings enclosed in single-quotes are treated almost literally, whereas the strings
delimited by the double quotes replaces variables with the string representations of their values as well
as specially interpreting certain escape sequences.
The escape-sequence replacements are:
\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 (\)
Example program :
<?php
$my_str = 'World';
echo "Hello, $my_str!<br>"; // Displays: Hello World!
echo 'Hello, $my_str!<br>'; // Displays: Hello, $my_str!
echo '<pre>Hello\tWorld!</pre>'; // Displays: Hello\tWorld!
echo "<pre>Hello\tWorld!</pre>"; // Displays: Hello World!
echo 'I\'ll be back'; Displays: I'll be back
?>
PHP provides nearly one hundred functions that can manipulate strings in various ways. Some (but not
all!) of the functions that can be performed on strings are:
There are no artificial limits on string length - within the bounds of available memory, you ought to be
able to make arbitrarily long strings.
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.
$string1="Hello World";
$string2="1234";
?>
The output is
Hello World 1234
The example below returns the length of the string "Hello world!":
<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello world!");
?>
</body>
</html>
The output is
12
Count The Number of Words in a String
<!DOCTYPE html>
<html>
<body>
<?php
echo str_word_count("Hello world!");
?>
</body>
</html>
The output is
2
<?php
echo strlen("Hello world!");
?>
12
The length of a string is often used in loops or other functions, when it is important to know
when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in
the string).
The strpos() function is used to search for a string or character within a string.
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.
<?php
?>
The result is 6.
Reverse a String
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match is
found, it will return FALSE.
The example below searches for the text "world" in the string "Hello world!":
<!DOCTYPE html>
<html>
<body>
<?php
echo strpos("Helloworld!", "world");
?>
</body>
</html>
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 ID c which
is called array 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
Create an Array in PHP
array();
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by numbers.
By default array index starts from zero. 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.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
</body>
</html>
This will produce the 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 :
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
</body>
</html>
This will produce the following result
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.
In the below 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.
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
</body>
</html>
The output is
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
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);
?>
The output is