0% found this document useful (0 votes)
9 views52 pages

PHP1

Uploaded by

Sambodh Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views52 pages

PHP1

Uploaded by

Sambodh Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Web Technology

PHP

Dr. Navanath Saharia


Indian Institute of Information Technology Senapati, Manipur
[email protected]

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 1 / 35
Introduction
b PHP is a server-side scripting language designed specifically for the Web

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 2 / 35
Introduction
b PHP is a server-side scripting language designed specifically for the Web
- What is server-side scripting language?

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 2 / 35
Introduction
b PHP is a server-side scripting language designed specifically for the Web
- What is server-side scripting language?
/ Language designed to be executed on the server of a web application

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 2 / 35
Introduction
b PHP is a server-side scripting language designed specifically for the Web
- What is server-side scripting language?
/ Language designed to be executed on the server of a web application
- Two primary components are involved in web development:
/ Client side: Refers to the user’s web browser, where HTML, CSS, and JavaScript are
processed and executed.
/ Server side: Refers to the host of the web application that handles request, process data,
and generate dynamic content.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 2 / 35
Introduction
b PHP is a server-side scripting language designed specifically for the Web
- What is server-side scripting language?
/ Language designed to be executed on the server of a web application
- Two primary components are involved in web development:
/ Client side: Refers to the user’s web browser, where HTML, CSS, and JavaScript are
processed and executed.
/ Server side: Refers to the host of the web application that handles request, process data,
and generate dynamic content.
- What is a web server?
/ Software that handles client requests and serves web content to users over the internet
- When a user requests a web page, the web server
/ processes that request,
/ executes server-side code(s) if any,
/ retrieves data from database(s) if any,
/ sends the result to the client’s web browser. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 2 / 35
Web server

b Example of web servers


- Nginx (https://nginx.org), developed by Russian developer
Igor Sysoev in 2004, known for its efficiency and load
balancing performance
- Apache (https://httpd.apache.org), developed by Robert
McCool in 1995, known for multiple request processing modes
and scalability
- Litghttpd (https://www.lighttpd.net), developed by Jan
Kneschkein in 2003, known for lightweightness and fast
processing capability. High-traffic websites, including
YouTube, Wikimedia Foundation, Meebo used Litghttpd as
hosting server
- Microsoft Internet Information Services (IIS,
https://www.iis.net), proprietary
- Google Web Server (GWS), proprietary, Google uses for its
web infrastructure
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 3 / 35
Introduction to Hypertext Preprocessor
b PHP is a server-side scripting language designed specifically for the Web

b PHP code is processed on a web server by a PHP interpreter implemented as a module/daemon/CGI


(Common Gateway Interface) and generates HTML

b PHP History

- 1993-94: Development stage, developed by Apache Software Engineer Rasmus Lerdorf


- 1995: Released with name Personal Home Page/Form Interpreter (PHP/FI)
- Current stable release 8.3.3 (https://www.php.net/downloads)

b Alternatives to PHP

- Practical extraction and Report Language (Perl)


- Active Server Pages (ASP)
- Java server pages (JSP)
- Ruby
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 4 / 35
Why PHP

b Open-source

b Easy to use (C-like syntax)

b Stable and fast

b Excellent support for interacting with databases

b Many built-in libraries and a large community for


support and ecosystem development

b Pre-installed in Linux distributions

b Embedded within HTML code, which allows


developer to mix server-side code with client-side
code seamlessly, simplifying the development process. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 5 / 35
First PHP Program

<html>
<head>
<title>PHP Example</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</html>

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 6 / 35
Introduction Variables

Variable
b Declared using a $ sign followed by the name of the variable. As loosely typed language, the
declaration of the data type of the variables are not required. Variable names are case-sensitive
$abc = 1.0; $bcd = "bcd"; $cde = true; $def = array("abc", "bcd", "cde");
b Superglobal Variables → Predefined variables that are accessible from any part of the script
regardless of scope.
- $_GET, $_POST, and $_REQUEST are used to access user input via URL parameters, HTTP POST
requests, and HTTP cookies in the form of associative array.
- $_SERVER is used to collect information about server environment
- $_COOKIE is used to collect HTTP cookie values in the form of an associative array
- $_ENV is used to collect information about the environment variables
- $_SESSION is used to store and retrieve user-specific data across multiple requests.
- $_FILES is used to access files that are uploaded via an HTTP POST request.
- $GLOBALS allows to access all global variables. Useful for debugging
b 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: Local, Global and Static
b The default sope is depends on, where the variables are declared/defined. PHP also has a concept
called class scope, which are based on access modifiers (public, private, or. protected)
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 7 / 35
Introduction Scope of variables

Local variable

b Local variables are variables that are declared within a function or method. They are only accessible
within the function where they are declared. Value of such variables are not accessible outside the
function’s curly braces {}

1 <?php
2 $abc = 3; /*global scope*/
3 function testFunction(){
4 var_dump($abc);
5 $abc = 1; /*local scope*/
6 var_dump($abc);
7 }
8 testFunction(); //output: NULL (with Warning: Undefined variable $abc)
9 //int(1)
10 var_dump($abc); //int(3)

b Local variables are limited to the scope in which they are declared, providing encapsulation and
helping to prevent naming conflicts
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 8 / 35
Introduction Scope of variables

Global variable

b Global variables in C are automatically available to functions unless specifically overridden by a local
definition. In PHP global variables must be declared global inside a function if they are going to be
used in that function

1 <?php
2 $abc = 3; $bcd = 0; /*Global scope*/
3 function testFunction(){
4 global $abc; /*1st approach I to use a global variable*/
5 $bcd = 2; /*Local scope*/
6 $GLOBALS['bcd'] = $GLOBALS['abc']; /*2nd approach to use a global variable*/
7 echo $abc. " ". $bcd;
8 }
9 testFunction(); //3 2
10 var_dump($bcd); //int(3)

b $GLOBALS is an associative array with the name of the global variable being the key and the contents
of that variable being the value of the array element
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 9 / 35
Introduction Scope of variables

Static variable

b Static variable are local variable that maintains its value across multiple calls. The static keyword is
used to define a static variable

1 <?php
2 function testFunction() {
3 static $abc = 0;
4 $abc++;
5 echo "value of abc: $abc\n";
6 }
7 testFunction(); //output: value of abc: 1
8 testFunction(); //output: value of abc: 2
9 testFunction(); //output: value of abc: 3

b Unlike local variables, static variables are not destroyed when a function finishes its execution.
Instead, they retain their values.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 10 / 35
Introduction Constant

Constant
b Identifiers that do not change during the execution of a script. Constant names are case-sensitive.
b Unlike variables, scope of constants are global across the entire script.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 11 / 35
Introduction Constant

Constant
b Identifiers that do not change during the execution of a script. Constant names are case-sensitive.
b Unlike variables, scope of constants are global across the entire script.
b Constant can be defined using two ways - Using define() function and const keyword
- define() function defines a named constant. Returns true on success and false otherwise.
/ Syntax: define("name", value);
/ Example: define("PI",3.1459); echo PI;

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 11 / 35
Introduction Constant

Constant
b Identifiers that do not change during the execution of a script. Constant names are case-sensitive.
b Unlike variables, scope of constants are global across the entire script.
b Constant can be defined using two ways - Using define() function and const keyword
- define() function defines a named constant. Returns true on success and false otherwise.
/ Syntax: define("name", value);
/ Example: define("PI",3.1459); echo PI;
- Using const keyword
/ Syntax: const name=value;
/ Example: const PI = 3.1459; echo PI;

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 11 / 35
Introduction Constant

Constant
b Identifiers that do not change during the execution of a script. Constant names are case-sensitive.
b Unlike variables, scope of constants are global across the entire script.
b Constant can be defined using two ways - Using define() function and const keyword
- define() function defines a named constant. Returns true on success and false otherwise.
/ Syntax: define("name", value);
/ Example: define("PI",3.1459); echo PI;
- Using const keyword
/ Syntax: const name=value;
/ Example: const PI = 3.1459; echo PI;
b Value of a constant may be another constant.
define("ABC", "nested??"); define("BCD", ABC); echo BCD; //output: nested??
b defined() function checks whether a constant with the given name is defined.
var_dump(defined("ABCD"));//output: bool(false)
b constant() function returns the value of the constant.
- The output echo PI; and echo constant("PI"); are equivalent. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 11 / 35
Introduction Constant

Magic constant

b Magic constant: Constants which get changed on


<?php
the basis of their use. Case-insensitive
namespace webClass;
b Used for debugging, logging, and generating dynamic class testClass {
information about the execution environment function testFunction() {
b __LINE__: Displays current line number. echo "\nCurrent line no: ".__LINE__;
echo "\nCurrent file: ".__file__;
b __FILE__: Displays full path and filename.
echo "\nCurrent dir: ".__DIR__;
b __DIR__: Displays directory of the file. echo "\nNamespace: ".__namespace__;
b __FUNCTION__: Displays current function name echo "\nCurrent class: ".__class__;
echo "\nFunction: ".__function__;
b __METHOD__: Displays current method name echo "\nCurrent method: ".__METHOD__;
b __CLASS__: Displays the name of the current class }
b __NAMESPACE__: Returns the current namespace }
$abc = new testClass();
b Magic constants are resolved at compile-time instead echo $abc->testFunction();
of run time, unlike the regular constant.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 12 / 35
Introduction Constant

__Trait__ : Magic constant


b Trait is a mechanism for code reuse in single inheritance languages, such as, PHP
b Similar to a class, but only intended to group functionality in a fine-grained and consistent way.
Traits are not instantiatable.
b Can contain/support methods, properties, visibility operators, and class operators (parent::, self::
and $this). use keyword is used to allow a class to use a trait

<?php
namespace webClass;
trait testTrait{
public function testLab(){
echo "\nCurrent trait: ".__trait__; output:
echo "\nCurrent class: ".__class__; Current trait: webClass\testTrait
echo "\nCurrent method: ".__method__; Current class: webClass\testClass
} Current method: webClass\testTrait::testLab
}
class testClass {use testTrait;}
$obj = new testClass();
. . . . . . . . . . . . . . . . . . . .
$obj->testLab(); . . . . . . . . . . . . . . . . . . . .
[email protected] PHP 13 / 35
Introduction Constant

classname::class : Magic constant


b Construct that deals with dynamic class creation or referencing classes from different namespaces.
The purpose of introducing the constant is to converts a class name (including namespaces) into its
fully qualified form at compile time.
<?php
namespace traitSpace;
trait testTrait{
public function testMethodConst(){return __method__;}
public function testClassConst(){return __class__;}
public function testClassName(){return testClass::class;}
}
class testClass {use testTrait;}
$obj = new testClass();
echo $obj->testMethodConst()."\n".$obj->testClassConst()."\n".$obj->testClassName();

/*output
traitSpace\testTrait::testMethodConst
traitSpace\testClass
. . . . . . . . . . . . . . . . . . . .
traitSpace\testClass . . . . . . . . . . . . . . . . . . . .

*/ [email protected] PHP 14 / 35
IO Statements Output

Output streams
b echo: Statement, displays one or more strings or values of variables to the browser.
- $courseName = " Web Technology "; $courseCode = 2015;
- echo $courseCode, $courseName; //output: 2015 Web Technology

b print: Statement, similar to echo, but it can output only one value/variable.
- print $courseCode; print $courseCode . $courseName; //note the concatenation

b printf: Function, displays formatted output. Does not return a value, it outputs directly to screen
- printf("Course name: %s, \tCourse code: %d", $courseCode, $courseName);

b sprintf: Function, returns the formatted string, which can be stored in a variable or used in
subsequent operations.
- sprintf("Course name: %s Course code: %d", $courseCode, $courseName);//no output
- $str = sprintf("Course name: %s, \tCourse code: %d", $courseCode, $courseName);
- $str = sprintf("select * from users where cName = '%s' ", $courseName);
- echo str;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 15 / 35
IO Statements Debugging

Debugging functions
b print_r: Displays content of a variable, such as an array or object, in human readable format.
<?php
$courseName = array("Web Technology", "DBMS", "Computer Network", "Theory of Computation");
echo $courseName; //output: Array with a warning: Array to string conversion
print $courseName; //output: Array with a warning: Array to string conversion
printf($courseName);//TypeError: printf(): Argument #1 ($format) must be of type string

print_r($courseName);

/*Output
Array
(
[0] => Web Technology
[1] => DBMS
[2] => Computer Network
[3] => Theory of Computation
)
. . . . . . . . . . . . . . . . . . . .
*/ ?> . . . . . . . . . . . . . . . . . . . .
[email protected] PHP 16 / 35
IO Statements Debugging

Debugging functions
b var_dump: Used for debugging and inspecting variables. It provides detailed information about a
variable, including its type and value
<?php
$courseName = array("Web Technology", "DBMS", "Computer Network", "Theory of Computation");
var_dump($courseName);

/*Output
array(4) {
[0]=>
string(14) "Web Technology"
[1]=>
string(4) "DBMS"
[2]=>
string(16) "Computer Network"
[3]=>
string(21) "Theory of Computation"
}
. . . . . . . . . . . . . . . . . . . .
*/ . . . . . . . . . . . . . . . . . . . .
[email protected] PHP 17 / 35
IO Statements Input

Input streams

b CLI-based mechanism
- Read one line: $line = trim(fgets(STDIN));
- Read multiple lines: fscanf(STDIN, "%d\n", $number);

b Form-based mechanism

b Cookies and Sessions

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 18 / 35
IO Statements Input

Dealing with HTML Form

b HTML Form in index.html


<form method="post" action="reDirect.php" >
<input type="text" name="cName" placeholder="Enter course name">
<input type="text" name="cCode" placeholder="Enter course code">
<input type="submit" value="Submit">
</form>

b PHP reDirect.php
<?php
$cName = $_POST['cName'];
$cCode = $_POST['cCode'];
echo "Course Name: ". $cName. "and code: ". $cCode;
?>

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 19 / 35
IO Statements Input

GET and POST method

b GET method appends data into the URL as query parameters, thus, limited by the maximum length
of a URL.
http://localhost/classTest/reDirect.php?cName=WebTechnology&cCode=CS2015

b However, the POST method sends data as a part of the body of the HTTP(S) request. Thus, POST
method can transmit larger amounts of data.
http://localhost/classTest/reDirect.php

b GET method is suitable for searching, filtering, and navigation, where state of the server will not
change. The POST method is suitable for form submissions, file uploads, and other actions that
change data on the server and contains sensitive information.
https://www.google.com/search?q=how+to+install+apache+&sca_esv=47...

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 20 / 35
IO Statements Input

Attributes of the Form element of HTML

b action: Specifies the URL to which the form data should be submitted when the user clicks the
submit button. <form action="submitForm.php" >

b method: Defines the HTTP method to be used when submitting the form. <form method="get">

b enctype: Specifies the encoding type used for sending data to the server when the form is submitted.
<form enctype="multipart/form-data">

b autocomplete: Specifies whether the browser should automatically complete the form values based
on the user’s input history. <form autocomplete="on">

b novalidate: Boolean attribute. If present, disables browser validation of form elements. Useful for
custom validation with JavaScript. <form novalidate>

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 21 / 35
IO Statements Input

Attributes of the Form element of HTML

b name: Assigns a name to the form, which can be used for scripting or styling purposes.
<form name="firstForm">

b Global attribute such as id, and class are also used for scripting or styling purposes.
<form name="firstForm" id="firstForm" class="firstForm">

b onsubmit: Defines a script to be run when the form is submitted.


<form onsubmit="return validateForm()">

b target: Specifies where to open the response from the server after form submission.
<form target="_blank">

b accept-charset: Specifies the character encodings that are to be used for the submission of the form
data. <form accept-charset="UTF-8">
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 22 / 35
Data Type Introduction

Types of Data

b Three types - Scalar, Compound, and Special

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 23 / 35
Data Type Introduction

Types of Data

b Three types - Scalar, Compound, and Special

b Scalar Type
- boolean
- integer
- float
- string

b Compound Type
- array
- object

b Special Type
- resource
- null
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 23 / 35
Data Type Scalar Type

Boolean Type
b Predefined constant with two values - True and False. Not case sensitive
b $a=true; $b=false; $c = (1 == 1); $d = (bool) 0; $e = (bool) "test";

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 24 / 35
Data Type Scalar Type

Boolean Type
b Predefined constant with two values - True and False. Not case sensitive
b $a=true; $b=false; $c = (1 == 1); $d = (bool) 0; $e = (bool) "test";
b Discuss the output of the following code segments
Segment I: $x=true; $y=false; var_dump($z=$y OR $x);
Segment II : $x=true; $y=false; $z=$y OR $x; var_dump($z);
Segment III : $x=true; $y=false; $z=$y || $x; var_dump($z);

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 24 / 35
Data Type Scalar Type

Boolean Type
b Predefined constant with two values - True and False. Not case sensitive
b $a=true; $b=false; $c = (1 == 1); $d = (bool) 0; $e = (bool) "test";
b Discuss the output of the following code segments
Segment I: $x=true; $y=false; var_dump($z=$y OR $x);
Segment II : $x=true; $y=false; $z=$y OR $x; var_dump($z);
Segment III : $x=true; $y=false; $z=$y || $x; var_dump($z);
The output of Segment II $z=$y OR $x; var_dump($z); is false, while other two are true. The OR
operator has lower precedence than assignment operator, thus, it will be like ($z=$y) OR $x rather
than $z=($y OR $x), whereas, in Segment II, the || operator has higher precedence than assignment.
Thus, the expression is equivalent to $z=($y || $x).
b When converting to bool, the following values are considered false: the boolean false itself, the integer
0, the floats 0.0 and -0.0, the empty string “”, the string “0”, an array with zero elements, the unit
type NULL and internal objects that overload their casting behaviour to bool.
Every other value is considered true.
b The (bool) cast is used to explicitly convert a value to bool
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 24 / 35
Data Type Scalar Type

Integer Type

b Represent whole numbers without decimal points. It can be octal, hexadecimal, +ve and -ve decimal
with range: -231 to 231 or zero.

b $a = 100; $b = 0100; $c = 0x45;

b echo PHP_INT_SIZE; is used to print the size of the integer in bytes. While echo PHP_INT_MAX; and
echo PHP_INT_MIN; are used to print maximum and minimum supporting integer.

b is_int($variableName), is_long($variableName) are functions to check whether a variable is of


type Integer or not.

b Check the output of $d = dechex($c); echo $d; and $e = 3.14; echo round($e);

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 25 / 35
Data Type Scalar Type

Floating Point Type

b Floating point numbers (also known as “floats”, “doubles”, or “real numbers”) can be specified using
any of the syntaxes: $a = 1.234; $b = 1.2e3; $c = 7E-10; $d = 1_234.567;

b PHP typically uses the IEEE 754 double precision format

b $x = 8 - 6.4; $y = 1.6; var_dump($x == $y);

b Do not compare floating point numbers directly for equality

b is_float($variableName), is_double($variableName), and is_real($variableName) are functions


to check whether a variable is of type Float or not.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 26 / 35
Data Type Scalar Type

Numeric literal separator

b Decimal: 1_000
b Scientific: 3.14_491_234e-12
b Float: 0.314_213_423_543_124_123
b Binary: 0b1001_0010_0001_1011_1111_1010_1110_1010
b Octal: 0123_456
b Hexa-decimal: 0xBEEF_BABE

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 27 / 35
Data Type Scalar Type

Numeric literal separator

b Decimal: 1_000
b Scientific: 3.14_491_234e-12
b Float: 0.314_213_423_543_124_123
b Binary: 0b1001_0010_0001_1011_1111_1010_1110_1010
b Octal: 0123_456
b Hexa-decimal: 0xBEEF_BABE
b Pattern which will generate errors
- Two or more underscores: 1__000
- Underscores before and after the number: _16 and 16_
- Underscore around the decimal point: 1_.6 or 1._6
- Underscore around number notation: 0_b01010 or 0_x_f00d or 3.1e_-12

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 27 / 35
Data Type Scalar Type

Strings
b A string is a sequence of chars
<?php $strTest = "this is a sequence of chars";
echo $strTest[0]; //output: t
echo $strTest; //output: this is a sequence of chars

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 28 / 35
Data Type Scalar Type

Strings
b A string is a sequence of chars
<?php $strTest = "this is a sequence of chars";
echo $strTest[0]; //output: t
echo $strTest; //output: this is a sequence of chars
b A single quoted strings is displayed as-it-is
<?php $age = 20;
$strTest = 'I am $age years old'; // output: I am $age years old
$strTest = "I am $age years old"; // output: I am 20 years old

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 28 / 35
Data Type Scalar Type

Strings
b A string is a sequence of chars
<?php $strTest = "this is a sequence of chars";
echo $strTest[0]; //output: t
echo $strTest; //output: this is a sequence of chars
b A single quoted strings is displayed as-it-is
<?php $age = 20;
$strTest = 'I am $age years old'; // output: I am $age years old
$strTest = "I am $age years old"; // output: I am 20 years old
b String concatenation
<?php $str = "This is "."a "."concatenated "."string";
echo $str; // output: is a composed string
$newStr = 'Also $str '.$str;
echo $newStr; // output: Also $str This is a concatenated string
b is_string($variableName) function finds whether a variable is of type String
. . . . .or
. .not.
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 28 / 35
Data Type Compound Type

Array-I

b Used to store a collection of values, which can be of different data types such as integers, strings, or
even other arrays
- $arr = array (1, "PHP", true, 3.14, array(10,20,30)); var_dump($arr);

b is_array($variableName) function finds whether a variable is of type Array or not.

b Types – Indexed, Associative, and Multi-dimensional arrays

b Indexed array: Array that stores/retrieve collections using numeric index.


- $langs = array ("PHP", "Python", "Perl", "Java", "C++"); echo $langs[0];

b Associative array: Array that stores/retrieves collection using key


- $langs = array(""=>"PHP",0=>"Perl",1=>"Python", 2=>3); echo $langs[""];
- To manipulate: $langs[0] = 'HTML'; var_dump($langs);
- Keys auto incremented if integer: $langs = array(5=>"PHP","Perl","Python"); Check with
echo $langs[6]; and var_dump($langs);
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 29 / 35
Data Type Compound Type

Array-II: Two-Dimensional Array


Array of array. Let us define a 3 × 3 matrix
<?php
  $matrix = array(
1 2 3 array(1,2,3),
4 5 6 array(4,5,6),
7 8 9 array(7,8,9)
);
?>
Retrieve elements from the matrix echo $matrix[1][1]; OR
<?php
for ($i = 0; $i < count($matrix); $i++) {
for ($j = 0; $j < count($matrix[$i]); $j++) {
echo $matrix[$i][$j] . " ";
}
echo "\n";
} .
.
.
.
.
. . . . .
. . . .
. . . .
. . . .
. . . .
. . . . .
.
.
.
.
.
.
.
.
.

?> [email protected] PHP 30 / 35


Data Type Compound Type

Array-III: Multi-Dimensional Array

b Multidimensional Array: Used to store data in a hierarchical structure


b Let us store the details of students in an array
$stdDB = array(
array('roll' => 101, 'name' => array('fn' => 'Round', 'ln' => 'Robin')),

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 31 / 35
Data Type Compound Type

Array-III: Multi-Dimensional Array

b Multidimensional Array: Used to store data in a hierarchical structure


b Let us store the details of students in an array
$stdDB = array(
array('roll' => 101, 'name' => array('fn' => 'Round', 'ln' => 'Robin')),
array('roll' => 102, 'name' => array('fn' => 'Mohan', 'ln' => 'Benu')),
array('roll' => 103, 'name' => array('fn' => 'Sakuntala', 'ln' => 'Devi')),
array('roll' => 104, 'name' => array('fn' => 'Amar Akbar', 'ln' => 'Anthony')) );

b Retrieving elements from the Array

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 31 / 35
Data Type Compound Type

Array-III: Multi-Dimensional Array

b Multidimensional Array: Used to store data in a hierarchical structure


b Let us store the details of students in an array
$stdDB = array(
array('roll' => 101, 'name' => array('fn' => 'Round', 'ln' => 'Robin')),
array('roll' => 102, 'name' => array('fn' => 'Mohan', 'ln' => 'Benu')),
array('roll' => 103, 'name' => array('fn' => 'Sakuntala', 'ln' => 'Devi')),
array('roll' => 104, 'name' => array('fn' => 'Amar Akbar', 'ln' => 'Anthony')) );

b Retrieving elements from the Array

- foreach($stdDB as $std) echo $std['roll'] . "\n";

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 31 / 35
Data Type Compound Type

Array-III: Multi-Dimensional Array

b Multidimensional Array: Used to store data in a hierarchical structure


b Let us store the details of students in an array
$stdDB = array(
array('roll' => 101, 'name' => array('fn' => 'Round', 'ln' => 'Robin')),
array('roll' => 102, 'name' => array('fn' => 'Mohan', 'ln' => 'Benu')),
array('roll' => 103, 'name' => array('fn' => 'Sakuntala', 'ln' => 'Devi')),
array('roll' => 104, 'name' => array('fn' => 'Amar Akbar', 'ln' => 'Anthony')) );

b Retrieving elements from the Array

- foreach($stdDB as $std) echo $std['roll'] . "\n";


- foreach($stdDB as $std) echo $std['name']['fn'] . "\n";

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 31 / 35
Data Type Compound Type

Array-III: Multi-Dimensional Array

b Multidimensional Array: Used to store data in a hierarchical structure


b Let us store the details of students in an array
$stdDB = array(
array('roll' => 101, 'name' => array('fn' => 'Round', 'ln' => 'Robin')),
array('roll' => 102, 'name' => array('fn' => 'Mohan', 'ln' => 'Benu')),
array('roll' => 103, 'name' => array('fn' => 'Sakuntala', 'ln' => 'Devi')),
array('roll' => 104, 'name' => array('fn' => 'Amar Akbar', 'ln' => 'Anthony')) );

b Retrieving elements from the Array

- foreach($stdDB as $std) echo $std['roll'] . "\n";


- foreach($stdDB as $std) echo $std['name']['fn'] . "\n";
- print_r(array_column($stdDB, 'roll')); [debugging purpose only]
- print_r($stdDB); or var_dump($stdDB); [debugging purpose only]
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 31 / 35
Data Type Compound Type

Object Type

b Represents an instance of a class. An object is created using the new keyword followed by the class
name and a set of parentheses
b Ways to define object: $a = new className();, $b = new class{};, and $c = (object)[];

$obj = new class{}; //Initialization of obj with anonymous class


$arr = array("one","two","three","four"); //Initialization of an Array
$obj = (object) $arr; //Type conversion
var_dump($obj);

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 32 / 35
Data Type Special Type

Resource Type

b Represents an external resource such as a file handle, database connection, image, or network socket

b Resource variables cannot be manipulated directly by PHP code, rather PHP has a dedicated set of
functions that interacts with an the system

b $fd = fopen("abc.txt", "r"); var_dump($fd); //resource(5) of type (stream)

b is_Resource($fd) function finds whether a variable is a resource or not.

b Resource variable needs to close properly after use to get rid of memory leakage.

b An active state of a variable is only considered as resource. For example:

$fd = fopen("abc.txt", "r"); var_dump(is_Resource($fd)); //true


fclose($fd); var_dump(is_Resource($fd)); //false
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 33 / 35
Data Type Special Type

NULL Type

b Represents a value that is undefined, non-existent, or absence of a value. For example: $a = NULL;

b NULL represents a lack of a value, it does not provide any information about the data type that the
value should be. For example: $a = 1; $a = null; var_dump(is_int($a));

b is_null($variableName) function is used to check if a value is NULL

b PHP automatically converts a value to a different data type if needed. This can lead to unexpected
behavior. For example: $a = null; $b = ""; var_dump(is_null($a)); var_dump(is_null($b));.
Variable $a is NULL variable and $b is a string, which is an empty. But var_dump($a == $b); will
generate true.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 34 / 35
Data Type Type Coercion

Type Coercion

b Process of automatic conversion of a value from one data type to another data type

b Contexts, when it may occur,


- When a variable is assigned a new value,
- When two values are compared
- When a value is passed as an argument to a function that expects a different data type

b String to Number: $a = "10"; $b = 10 + $a; var_dump($b); var_dump(is_integer($b));

b Number to String: $a = "10"; $b = 10 . $a; var_dump($b); var_dump(is_integer($b));

b Boolean to Number: $a = true; $b = 10 + $a; var_dump($b); var_dump(is_bool($b));

b String to Boolean: $a = ""; $b = "0"; $c = "1"; if($a) echo "True"; else echo "False";

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 35 / 35

You might also like