0% found this document useful (0 votes)
5 views

Unit I PHP

PHP, or Hypertext Preprocessor, is a popular open-source scripting language primarily used for web development, known for its simplicity and flexibility. It has evolved since its introduction in 1994, with significant versions enhancing performance and features, including support for object-oriented programming and Just-In-Time compilation. PHP supports various data types, operators, and variable scopes, making it versatile for applications like dynamic web pages, content management systems, and e-commerce platforms.

Uploaded by

romeyoremo900
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit I PHP

PHP, or Hypertext Preprocessor, is a popular open-source scripting language primarily used for web development, known for its simplicity and flexibility. It has evolved since its introduction in 1994, with significant versions enhancing performance and features, including support for object-oriented programming and Just-In-Time compilation. PHP supports various data types, operators, and variable scopes, making it versatile for applications like dynamic web pages, content management systems, and e-commerce platforms.

Uploaded by

romeyoremo900
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT I – INTRODUCTION TO PHP

What is PHP?

PHP, which stands for Hypertext Preprocessor, is a widely-used, open-source


scripting language designed primarily for web development. It is executed on the server,
and the result is returned to the browser as plain HTML. PHP is known for its simplicity,
flexibility, and efficiency, making it a popular choice for both beginners and experienced
developers..

History of PHP

PHP was introduced by Rasmus Lerdorf in 1994, the first version and participated in
the later versions. It is an interpreted language and it does not require a compiler. The
language quickly evolved and was given the name “PHP,” which initially named was
“Personal Home Page.”

• PHP 3 (1998): The first version considered suitable for widespread use.

• PHP 4 (2000): Improved performance and the introduction of the Zend Engine.

• PHP 5 (2004): Added object-oriented programming features.

• PHP 7 (2015): Significant performance improvements and reduced memory usage.

• PHP 8 (2020): Introduction of Just-In-Time (JIT) compilation, further enhancing


performance.

Characteristics of PHP

• PHP code is executed in the server.

• It can be integrated with many databases such as Oracle, Microsoft SQL Server.

• It supports main protocols like HTTP Basic, HTTP Digest, IMAP, FTP, and others.

• Websites like www.facebook.com and www.yahoo.com are also built on PHP.

• One of the main reasons behind this is that PHP can be easily embedded in HTML
files and HTML codes can also be written in a PHP file.

Syntax

<?php

// PHP code goes here

?>
Basic Example of PHP

<!DOCTYPE html>

<html>

<head>

<title>PHP Hello World</title>

</head>

<body>

<?php echo "Hello, World! This is PHP code";?>

</body>

</html>

Output:

Hello, World! This is PHP code

Features of PHP

• Dynamic Typing: PHP is dynamically typed, meaning you don’t need to declare the
data type of a variable explicitly.

• Cross-Platform: PHP runs on various platforms, making it compatible with different


operating systems.

• Database Integration: PHP provides built-in support for interacting with databases,
such as MySQL, PostgreSQL, and others.

• Server-Side Scripting: PHP scripts are executed on the server, generating HTML that
is sent to the client’s browser.

Applications of PHP

PHP is versatile and can be used in a variety of web development scenarios, including:

• Dynamic Web Pages: Generating dynamic content based on user interaction or other
conditions.

• Content Management Systems (CMS): Many popular CMSs like WordPress, Joomla,
and Drupal are built with PHP.
• E-commerce Platforms: PHP is commonly used to develop e-commerce websites due
to its database integration capabilities.

• Web Applications: PHP is used for creating feature-rich web applications such as
social media platforms, forums, and customer relationship management (CRM)
systems.

• API Development: PHP can be used to create APIs for web and mobile applications.

Advantages of PHP

• Open Source: PHP is an open-source language, meaning it is freely available for


anyone to use and distribute.

• Easy to Learn: The syntax of PHP is quite similar to C and other programming
languages. This makes PHP relatively easy to learn, especially for developers who
already have some programming experience.

• Database Support: PHP has excellent support for various databases, including
MySQL, PostgreSQL, SQLite, and more. This makes it easy to connect and interact
with databases, a crucial aspect of many web applications.

• Server-Side Scripting: PHP scripts are executed on the server, reducing the load on
the client’s side. This server-side scripting capability is crucial for generating dynamic
content and performing server-related tasks.

• Community Support: The PHP community actively contributes to the language’s


development, ensuring regular updates, security patches, and improvements.

Disadvantages of PHP

• Security Concerns: If not handled properly, PHP code may be susceptible to security
vulnerabilities, such as SQL injection and cross-site scripting (XSS). Developers need
to be cautious and follow best practices to secure PHP applications.

• Performance: While PHP performs well for many web applications, it may not be as
fast as some compiled languages like C or Java. However, advancements and
optimizations in recent versions have improved performance.

• Lack of Modern Features: Compared to newer languages, PHP may lack some
modern language features. However, recent versions of PHP have introduced
improvements and features to address this concern.
• Limited OOP’S Support: Although PHP supports OOP, its implementation has been
criticized for not being as robust as in some other languages. However, recent
versions have introduced improvements to enhance OOP capabilities.

Essential Of PHP
Variables:

In PHP, a variable is declared using a $ sign followed by the variable name. Here, some
important points to know about variables:

o As PHP is a loosely typed language, so we do not need to declare the data types of
the variables. It automatically analyzes the values and makes conversions to its
correct datatype.

o After declaring a variable, it can be reused throughout the code.

o Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:

$variablename=value;

Rules for declaring PHP variable:

o A variable must start with a dollar ($) sign, followed by the variable name.

o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).

o A variable name must start with a letter or underscore (_) character.

o A PHP variable name cannot contain spaces.

o PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.

Example :

<?php
$str="hello string";
$x=200;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
?>
Output:

string is: hello string

integer is: 200

PHP Variable Scope

The scope of a variable is defined as its range in the program under which it can be
accessed. In other words, "The scope of a variable is the portion of the program within
which it is defined and can be accessed."

PHP has three types of variable scopes:

1. Local variable

2. Global variable

3. Static variable

Local variable

Local variables are declared inside a function or method and are only accessible
within that function. They do not exist outside the function's scope.

Example:

<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output:

Local variable declared inside the function is: 45

Global variable

Global variables are declared outside of any function and can be accessed from
anywhere in the script. You need to use the global keyword inside a function to modify a
global variable.
Example:

<?php
$name = "Ram"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Output:

Variable inside the function: Ram

Variable outside the function: Ram

Static variable

Static variables are local variables that retain their values between function calls.
They are initialized only once when the function is first called.

Example:

<?php
function static_var()
{
static $num1 = 3; //static variable
$num1++;

echo "Static: " .$num1 ."</br>";

static_var();

?>
Output:

Static: 4

PHP Data Types

PHP data types are used to hold different types of data or values. PHP supports 8
primitive data types that can be categorized further in 3 types:

1. Scalar Types (predefined)

2. Compound Types (user-defined)

3. Special Types

PHP Data Types: Scalar Types

It holds only single value. There are 4 scalar data types in PHP.

1. boolean

2. integer

3. float

4. string

PHP Data Types: Compound Types

It can hold multiple values. There are 2 compound data types in PHP.

1. array

2. object

PHP Data Types: Special Types

There are 2 special data types in PHP.

1. resource

2. NULL

Integer (int):

The integer data type represents whole numbers, both positive and negative,
without a fractional or decimal component.

Examples of integers include -42, 0, and 100.

$age = 30; // an integer variable


Floating-Point (float or double):

Floating-point data types represent numbers with a decimal point or in scientific


notation.

Examples include 3.14159, -0.01, and 2.5e3.

$pi = 3.14159; // a floating-point variable

String:

The string data type represents sequences of characters, such as text. Strings can be
enclosed in single quotes (') or double quotes (").

$name = "John"; // a string variable 4.

Boolean (bool):

Boolean data types represent one of two possible values: true or false. Booleans are
often used for conditional statements and comparisons.

$isMember = true; // a boolean variable

Comments:

• PHP supports two types of comments:


• Single-line comments: These begin with // and extend to the end of the line.
• Multi-line comments: These start with /* and end with */.

// This is a single-line comment

/* This is a multi-line comment that spans multiple lines */

PHP Operators

Operators are used to performing operations on some values. In other words, we can
describe operators as something that takes some values, performs some operation on
them, and gives a result.

Given below are the various groups of operators:

• Arithmetic Operators

• Logical or Relational Operators

• Comparison Operators

• Conditional or Ternary Operators


• Assignment Operators

• Spaceship Operators (Introduced in PHP 7)

• Array Operators

• Increment/Decrement Operators

• String Operators

Let us now learn about each of these operators in detail.

Arithmetic Operators:

The arithmetic operators are used to perform simple mathematical operations like addition,
subtraction, multiplication, etc. Below is the list of arithmetic operators along with their
syntax and operations in PHP.

Operator Name Syntax

+ Addition $x + $y

– Subtraction $x – $y

* Multiplication $x * $y

/ Division $x / $y

** Exponentiation $x ** $y

% Modulus $x % $y

Example:

<?php

// Define two numbers

$x = 10;
$y = 3;

// Addition

echo "Addition: " . ($x + $y) . "<br>";

// Subtraction

echo "Subtraction: " . ($x - $y) . "<br>";

// Multiplication

echo "Multiplication: " . ($x * $y) . "<br>";

// Division

echo "Division: " . ($x / $y) . "<br>";

// Exponentiation

echo "Exponentiation: " . ($x ** $y) . "<br>";

// Modulus

echo "Modulus: " . ($x % $y) . "<br>";

?>

Output

Addition: 13

Subtraction: 7

Multiplication: 30

Division: 3.3333333333333

Exponentiation: 1000

Modulus: 1

Logical or Relational Operators:

These are basically used to operate with conditional statements and expressions.
Conditional statements are based on conditions. Also, a condition can either be met or
cannot be met so the result of a conditional statement can either be true or false. Here are
the logical operators along with their syntax and operations in PHP.
Operator Name Syntax

and Logical AND $x and $y

or Logical OR $x or $y

xor Logical XOR $x xor $y

Example:

<?php

$x = 50;

$y = 30;

if ($x == 50 and $y == 30)

echo "and Success <br>";

if ($x == 50 or $y == 20)

echo "or Success <br>";

if ($x == 50 xor $y == 20)

echo "xor Success <br>";

Output:

and Success
or Success
xor Success

Comparison Operators:

These operators are used to compare two elements and outputs the result in
boolean form. Here are the comparison operators along with their syntax and operations in
PHP.
Operator Name Syntax

== Equal To $x == $y

!= Not Equal To $x != $y

<> Not Equal To $x <> $y

=== Identical $x === $y

!== Not Identical $x == $y

< Less Than $x < $y

> Greater Than $x > $y

<= Less Than or Equal To $x <= $y

>= Greater Than or Equal To $x >= $y

Example:

<?php

$a = 80;

$b = 50;

$c = "80";

var_dump($a == $c) + "<br>";

var_dump($a != $b) + "<br>";

var_dump($a <> $b) + "<br>";

var_dump($a === $c) + "<br>";


var_dump($a !== $c) + "<br>";

var_dump($a < $b) + "<br>";

var_dump($a > $b) + "<br>";

var_dump($a <= $b) + "<br>";

var_dump($a >= $b);

?>

Output:

bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)

Conditional or Ternary Operators:

These operators are used to compare two values and take either of the results
simultaneously, depending on whether the outcome is TRUE or FALSE. These are also used
as a shorthand notation for if…else statement that we will read in the article on decision
making.

Syntax:

$var = (condition)? value1 : value2;

Here, the condition will either evaluate as true or false. If the condition evaluates to True,
then value1 will be assigned to the variable $var otherwise value2 will be assigned to it.

Operator Name Operation

If the condition is true? then $x : or else $y. This means that if the
?: Ternary condition is true then the left result of the colon is accepted
otherwise the result is on right.
Example:

<?php

$x = -12;

echo ($x > 0) ? 'The number is positive' : 'The number is negative';

?>

Output:

The number is negative

Assignment Operators:

These operators are used to assign values to different variables, with or without mid-
operations. Here are the assignment operators along with their syntax and operations, that
PHP provides for the operations.

Operator Name Syntax

= Assign $x = $y

+= Add then Assign $x += $y

-= Subtract then Assign $x -= $y

*= Multiply then Assign $x *= $y

/= Divide then Assign (quotient) $x /= $y

%= Divide then Assign (remainder) $x %= $y

Example:

<?php

// Simple assign operator

$y = 75;
echo $y, "<br>";

// Add then assign operator

$y = 100;

$y += 200;

echo $y, "<br>";

// Subtract then assign operator

$y = 70;

$y -= 10;

echo $y, "<br>";

// Multiply then assign operator

$y = 30;

$y *= 20;

echo $y, "<br>";

// Divide then assign(quotient) operator

$y = 100;

$y /= 5;

echo $y, "<br>";

// Divide then assign(remainder) operator

$y = 50;

$y %= 5;

echo $y;

?>

Output:

75
300
60
600
20
0

Array Operators:

These operators are used in the case of arrays. Here are the array operators along
with their syntax and operations, that PHP provides for the array operation.

Operator Name Syntax Operation

+ Union $x + $y Union of both i.e., $x and $y

== Equality $x == $y Returns true if both has same key-value pair

!= Inequality $x != $y Returns True if both are unequal

Returns True if both have the same key-value pair in


=== Identity $x === $y
the same order and of the same type

!== Non-Identity $x !== $y Returns True if both are not identical to each other

<> Inequality $x <> $y Returns True if both are unequal

Increment/Decrement Operators:

These are called the unary operators as they work on single operands. These are
used to increment or decrement values.

Operator Name Syntax Operation

++ Post-Increment $x++ First returns $x, then increment it by one

— Post-Decrement $x– First returns $x, then decrement it by one


String Operators:

This operator is used for the concatenation of 2 or more strings using the
concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to
append the argument on the right side to the argument on the left side.

Operator Name Syntax Operation

. Concatenation $x.$y Concatenated $x and $y

Concatenation and First concatenates then assigns, same as


.= $x.=$y
assignment $x = $x.$y

Example:

<?php

$x = "Geeks";

$y = "for";

$z = "Geeks!!!";

echo $x . $y . $z, "<br>";

$x .= $y . $z;

echo $x;

?>

Output:

GeeksforGeeks!!!
GeeksforGeeks!!!

PHP | Decision Making

PHP allows us to perform actions based on some type of conditions that may be
logical or comparative. Based on the result of these conditions i.e., either TRUE or FALSE, an
action would be performed as asked by the user.
• if statement

• if…else statement

• if…elseif…else statement

• switch statement

if Statement:

The if statement is used for conditional execution. It runs a block of code if a


specified condition is true.

If statement is used to executes the block of code exist inside the if statement only if
the specified condition is true.

Syntax

if(condition){

//code to be executed }

Example

<?php

$num=12;

if($num<100){

echo "$num is less than 100";

?>

Output:

12 is less than 100

If-else Statement

PHP if-else statement is executed whether condition is true or false.

If-else statement is slightly different from if statement. It executes one block of code
if the specified condition is true and another block of code if the condition is false.
Syntax

if(condition){

//code to be executed if true

}else{

//code to be executed if false

Example

<?php

$num=12;

if($num%2==0){

echo "$num is even number";

}else{

echo "$num is odd number";

?>

Output:

12 is even number

If-else-if Statement

The PHP if-else-if is a special statement used to combine multiple if?.else statements.
So, we can check multiple conditions using this statement.

Syntax

if (condition1){

//code to be executed if condition1 is true

} elseif (condition2){

//code to be executed if condition2 is true

} else{

//code to be executed if all given conditions are false }


Example:

<?php

$x = "August";

if ($x == "January") {

echo "Happy Republic Day";

elseif ($x == "August") {

echo "Happy Independence Day!!!";

else{

echo "Nothing to show";

?>

Output:

Happy Independence Day!!!

Switch Statement:

The switch statement is used to select one of many code blocks to be executed.

Syntax :

switch (expression)

{ case value1: // Code to execute when expression equals value1

break;

case value2: // Code to execute when expression equals value2

break; //

Additional cases...

default: // Code to execute when no case matches

}
Example:

<?php

$n = "February";

switch($n) {

case "January":

echo "Its January";

break;

case "February":

echo "Its February";

break;

case "March":

echo "Its March";

break;

default:

echo "Doesn't exist";

?>

Output:

Its February

PHP Loops

1. While Loop:

The while loop repeatedly executes a block of code as long as a specified condition is
true.

Syntax :

while (condition) {

// Code to execute as long as the condition is true

}
Example :

<?php

$count = 1;

while ($count <= 5) {

echo "Count: $count<br>";

$count++;

?>

Output :

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

2.do while Loop:

The do-while loop is very similar to the while loop, the only difference is that the do-
while loop checks the expression (condition) at the end of each iteration.

Syntax:

do {

// Code is executed

} while (if the condition is true);

Example :

<?php

$num = 10;

do

echo $num . "<br>";

$num += 2;
} while ($num < 20);

?>

Output

10

12

14

16

18

3. for Loop:

The for loop is used to iterate a specific number of times.

It consists of three expressions:

• Initialization: Sets the initial value of the loop variable.

• Condition: Checks if the loop should continue.

• Increment/Decrement: Changes the loop variable after each iteration.

Syntax :

for (initialization; condition; increment) {

// Code to execute as long as the condition is true

Example :

<?php

for ($i = 1; $i <= 5; $i++) {

echo "Iteration $i <br>";

?>

Output :

Iteration 1
Iteration 2

Iteration 3

Iteration 4

Iteration 5

3. foreach Loop:

The foreach loop is used to iterate over elements in an array or other iterable
objects.

Syntax :

foreach ($array as $value) {

// Code to execute for each element in the array

Example :

<?php

$fruits = ["apple", "banana", "cherry"];

foreach ($fruits as $fruit) {

echo "I like $fruit<br>";

?>

Output:

I like apple
I like banana
I like cherry

PHP String

PHP string is a sequence of characters i.e., used to store and manipulate text. PHP
supports only 256-character set and so that it does not offer native Unicode support. There
are 4 ways to specify a string literal in PHP.

1. single quoted

2. double quoted
3. heredoc syntax

4. newdoc syntax (since PHP 5.3)

Single Quoted

We can create a string in PHP by enclosing the text in a single-quote. It is the easiest
way to specify string in PHP.

For specifying a literal single quote, escape it with a backslash (\) and to specify a
literal backslash (\) use double backslash (\\).

Example

<?php

$str='Hello text within single quote';

echo $str;

?>

Output:

Hello text within single quote

Double Quoted

In PHP, we can specify string through enclosing text within double quote also. But
escape sequences and variables will be interpreted using double quote PHP strings.

Example

<?php

$str="Hello text within double quote";

echo $str;

?>

Output:

Hello text within double quote

Now, you can't use double quote directly inside double quoted string.

Heredoc

Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an
identifier is provided after this heredoc <<< operator, and immediately a new line is started
to write any text. To close the quotation, the string follows itself and then again that same
identifier is provided.

Example

<?php

$str = <<<Demo

It is a valid example

Demo; //Valid code as whitespace or tab is not valid before closing identifier

echo $str;

?>

Output:

It is a valid example

Nowdoc :

Nowdoc is very much similar to the heredoc other than the parsing done in
heredoc. The syntax is similar to the heredoc syntax with symbol <<< followed by an
identifier enclosed in single-quote. The rule for nowdoc is the same as heredoc.

Example:

<?php

$str = <<<'DEMO'

Welcome to javaTpoint. Learn with newdoc example.

DEMO;

echo $str;

echo '</br>';

echo <<< 'Demo' // Here we are not storing string content in variable str.

Welcome to javaTpoint. Learn with newdoc example.

Demo;

?>
Output:

Welcome to javaTpoint. Learn with newdoc example.

Welcome to javaTpoint. Learn with newdoc example.

Common PHP String Functions

1. PHP strlen() Function

This function takes a string as argument and returns and integer value representing
the length of string. It calculates the length of the string including all the whitespaces and
special characters.

Syntax

strlen( $string )

Example: Counts the string length using strlen() function.

<?php

$str = "welcome to GeeksforGeeks";

$len = strlen($str);

echo "String Length: " . $len;

?>

Output

String Length: 24

2. PHP str_word_count() Function

The str_word_count() function counts the number of words in a string.

Syntax

str_word_count( string $string, int $format = 0 ): mixed

Example: Count the words of a string using str_word_count() function.

<?php

$str = "Welcome to GeeksforGeeks";

$count = str_word_count($str);

echo "Word Counr: " . $count;


?>

Output

Word Counr: 3

3. PHP strrev() Function

The strrev() function reverses a string.

Syntax

strrev( string $string ): string

Example: Reverse the given string using strrev() function.

<?php

$str = "Welcome to GeeksforGeeks";

echo strrev($str);

?>

Output

skeeGrofskeeG ot emocleW

4. PHP strtoupper() Function

The strtoupper() function takes a string as argument and returns the string with all
characters in Upper Case.

Syntax

strtoupper( $string )

Example: Convert the text to uppercase using strtoupper() function.

<?php

$str = "geeksforgeeks";

$upperCase = strtoupper($str);

echo $upperCase;

?>

Output

GEEKSFORGEEKS
5. PHP strtolower() Function

This function takes a string as argument and returns the string with all of the
characters in Lower Case.

Syntax

strtolower( $string )

Example: Convert the text to lower case using strtolower() function.

<?php

$str = "GEEKSFORGEEKS";

$lowerCase = strtolower($str);

echo $lowerCase;

?>

Output

geeksforgeeks

6. PHP ucfirst() Function

This function takes a string as argument and returns the string with the first character
in Upper Case and all other cases of the characters remains unchanged.

Syntax

ucfirst( $string )

Example: Convert the first letter of string to upper case using ucfirst() function.

<?php

$str = "welcome to geeksforgeeks";

$firstUpper = ucfirst($str);

echo $firstUpper;

?>

Output

Welcome to geeksforgeeks
7. PHP lcfirst() Function

This function takes a string as argument and returns the string with the first character
in Lower Case and all other characters remains unchanged.

Syntax

lcfirst( $string )

Example: Convert the first letter string to lower case using lcfirst() function.

<?php

$str = "WELCOME to GeeksforGeeks";

$firstLower = lcfirst($str);

echo $firstLower;

?>

Output

wELCOME to GeeksforGeeks

8. PHP ucwords() Function

This function takes a string as argument and returns the string with the first character
of every word in Upper Case and all other characters remains unchanged.

Syntax

ucwords( $string )

Example: Convert the first letter of each words to uppercase using ucwords() function.

<?php

$str = "welcome to geeksforgeeks";

$firstUpper = ucwords($str);

echo $firstUpper;

?>

Output

Welcome To Geeksforgeeks
PHP Arrays

PHP array is an ordered map (contains value on the basis of key). It is used to hold
multiple values of similar type in a single variable.

Advantage of PHP Array

Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types

There are 3 types of array in PHP.

1. Indexed Array

2. Associative Array

3. Multidimensional Array

PHP Indexed Array

PHP index is represented by number which starts from 0. We can store number,
string and object in the PHP array. All PHP array elements are assigned to an index number
by default.

There are two ways to define indexed array:

1st way:

1. $season=array("summer","winter","spring","autumn");

2nd way:

1. $season[0]="summer";

2. $season[1]="winter";

3. $season[2]="spring";

4. $season[3]="autumn";

Example:

<?php

$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";

?>

Output:

Season are: summer, winter, spring and autumn

PHP Associative Array

We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

2nd way:

1. $salary["Sonoo"]="350000";

2. $salary["John"]="450000";

3. $salary["Kartik"]="200000";

Example:

<?php

$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";

echo "John salary: ".$salary["John"]."<br/>";

echo "Kartik salary: ".$salary["Kartik"]."<br/>";

?>

Output :

Sonoo salary: 350000

John salary: 450000

Kartik salary: 200000


PHP Multidimensional Array

PHP multidimensional array is also known as array of arrays. It allows you to store
tabular data in an array. PHP multidimensional array can be represented in the form of
matrix which is represented by row * column.

Example :

$emp = array

array(1,"sonoo",400000),

array(2,"john",500000),

array(3,"rahul",300000)

);

You might also like