PHP Notes1
PHP Notes1
PHP tutorial for beginners and professionals provides in-depth knowledge of PHP scripting
language. Our PHP tutorial will help you to learn PHP scripting language easily.
This PHP tutorial covers all the topics of PHP such as introduction, control statements, functions,
array, string, file handling, form handling, regular expression, date and time, object-oriented
programming in PHP, math, PHP MySQL, PHP with Ajax, PHP with jQuery and PHP with XML.
What is PHP
PHP is an open-source, interpreted, and object-oriented scripting language that can be executed
at the server-side. PHP is well suited for web development. Therefore, it is used to develop web
applications (an application that executes on the server and generates the dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 7.4.0 is the
latest version of PHP, which was released on 28 November. Some important points need to be
noticed about PHP are as followed:
o PHP stands for Hypertext Preprocessor.
o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the dynamic content of
the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.
o WAMP for Windows
o LAMP for Linux
o MAMP for Mac
o SAMP for Solaris
o FAMP for FreeBSD
o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
Step 2: After downloading XAMPP, double click on the downloaded file and allow XAMPP to make
changes in your system. A window will pop-up, where you have to click on the Next button.
Step 3: Here, select the components, which you want to install and click Next.
Step 4: Choose a folder where you want to install the XAMPP in your system and click Next.
Step 7: A finish window will display after successful installation. Click on the Finish button.
Step 8: Choose your preferred language.
Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run the php program on
the localhost.
How to run PHP programs on XAMPP, see in the next tutorial.
Most of the time, PHP programs run as a web server module. However, PHP can also be run on CLI
(Command Line Interface).
PHP Case Sensitivity
In PHP, keyword (e.g., echo, if, else, while), functions, user-defined functions, classes are not case-
sensitive. However, all variable names are case-sensitive.
In the below example, you can see that all three echo statements are equal and valid:
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "Hello world using echo </br>";
6. ECHO "Hello world using ECHO </br>";
7. EcHo "Hello world using EcHo </br>";
8. ?>
9. </body>
10. </html>
Output:
Hello world using echo
Hello world using ECHO
Hello world using EcHo
Look at the below example that the variable names are case sensitive. You can see the example
below that only the second statement will display the value of the $color variable. Because it
treats $color, $ColoR, and $COLOR as three different variables:
1. <html>
2. <body>
3. <?php
4. $color = "black";
5. echo "My car is ". $ColoR ."</br>";
6. echo "My dog is ". $color ."</br>";
7. echo "My Phone is ". $COLOR ."</br>";
8. ?>
9. </body>
10. </html>
Output:
Notice: Undefined variable: ColoR in D:\xampp\htdocs\program\p2.php on line 8
My car is
My dog is black
1. void echo ( string $arg1 [, string $... ] )
PHP echo statement can be used to print the string, multi-line strings, escaping characters,
variable, array, etc. Some important points that you must know about the echo statement are:
1. <?php
2. echo "Hello by PHP echo";
3. ?>
Output:
Hello by PHP echo
PHP echo: printing multi line string
File: echo2.php
1. <?php
2. echo "Hello by PHP echo
3. this is multi line
4. text printed by
5. PHP echo statement
6. ";
7. ?>
Output:
Hello by PHP echo this is multi line text printed by PHP echo statement
PHP echo: printing escaping characters
File: echo3.php
1. <?php
2. echo "Hello escape \"sequence\" characters";
3. ?>
Output:
Hello escape "sequence" characters
PHP echo: printing variable value
File: echo4.php
1. <?php
2. $msg="Hello JavaTpoint PHP";
3. echo "Message is: $msg";
4. ?>
Output:
Message is: Hello JavaTpoint PHP
PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the
argument list. Print statement can be used with or without parentheses: print and print(). Unlike
echo, it always returns 1.
The syntax of PHP print is given below:
1. int print(string $arg)
PHP print statement can be used to print the string, multi-line strings, escaping characters,
variable, array, etc. Some important points that you must know about the echo statement are:
o print is a statement, used as an alternative to echo at many times to display the output.
1. <?php
2. print "Hello by PHP print ";
3. print ("Hello by PHP print()");
4. ?>
Output:
Hello by PHP print Hello by PHP print()
PHP print: printing multi line string
File: print2.php
1. <?php
2. print "Hello by PHP print
3. this is multi line
4. text printed by
5. PHP print statement
6. ";
7. ?>
Output:
Hello by PHP print this is multi line text printed by PHP print statement
PHP print: printing escaping characters
File: print3.php
1. <?php
2. print "Hello escape \"sequence\" characters by PHP print";
3. ?>
Output:
Hello escape "sequence" characters by PHP print
PHP print: printing variable value
File: print4.php
1. <?php
2. $msg="Hello print() in PHP";
3. print "Message is: $msg";
4. ?>
Output:
Message is: Hello print() in PHP
PHP echo and print Statements
We frequently use the echo statement to display the output. There are two basic ways to get the
output in PHP:
o echo
o print
echo and print are language constructs, and they never behave like a function. Therefore, there is
no requirement for parentheses. However, both the statements can be used with or without
parentheses. We can use these statements to output variables or strings.
Difference between echo and print
echo
o print is also a statement, used as an alternative to echo at many times to display the
output.
1. <?php
2. $fname = "Gunjan";
3. $lname = "Garg";
4. echo "My name is: ".$fname,$lname;
5. ?>
Output:
1. <?php
2. $fname = "Gunjan";
3. $lname = "Garg";
4. print "My name is: ".$fname,$lname;
5. ?>
Output:
1. <?php
2. $lang = "PHP";
3. $ret = echo $lang." is a web development language.";
4. echo "</br>";
5. echo "Value return by print statement: ".$ret;
6. ?>
Output:
1. <?php
2. $lang = "PHP";
3. $ret = print $lang." is a web development language.";
4. print "</br>";
5. print "Value return by print statement: ".$ret;
6. ?>
Output:
PHP Variables
<="" p="" style="color: rgb(0, 0, 0); font-family: verdana, helvetica, arial, sans-serif; font-size: 14px;
font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400;
letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-
space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color:
rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-
color: initial;">
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.
1. $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 One thing to be kept in mind that the variable name cannot start with a number or special
symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.
PHP Variable: Declaring string, integer, and float
Let's see the example to store string, integer, and float values in PHP variables.
File: variable1.php
1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Output:
string is: hello string
integer is: 200
float is: 44.6
PHP Variable: Sum of two variables
File: variable2.php
1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>
Output:
11
PHP Variable: case sensitive
In PHP, variable names are case sensitive. So variable name "color" is different from Color, COLOR,
COLor etc.
File: variable3.php
1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>
Output:
My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is
PHP Variable: Rules
PHP variables must start with letter or underscore only.
PHP variable can't be start with numbers and special symbols.
File: variablevalid.php
1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>
Output:
hello
hello
File: variableinvalid.php
1. <?php
2. $4c="hello";//number (invalid)
3. $*d="hello";//special symbol (invalid)
4.
5. echo "$4c <br/> $*d";
6. ?>
Output:
Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE)
or '$' in C:\wamp\www\variableinvalid.php on line 2
PHP: Loosely typed language
PHP is a loosely typed language, it means PHP automatically converts the variable to its correct
data type.
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
The variables that are declared within a function are called local variables for that function. These
local variables have their scope only in that particular function in which they are declared. This
means that these variables cannot be accessed outside the function, as they have local scope.
A variable declaration outside the function with the same name is completely different from the
variable declared inside the function. Let's understand the local variables with the help of an
example:
File: local_variable1.php
1. <?php
2. function local_var()
3. {
4. $num = 45; //local variable
5. echo "Local variable declared inside the function is: ". $num;
6. }
7. local_var();
8. ?>
Output:
Local variable declared inside the function is: 45
File: local_variable2.php
1. <?php
2. function mytest()
3. {
4. $lang = "PHP";
5. echo "Web development language: " .$lang;
6. }
7. mytest();
8. //using $lang (local variable) outside the function will generate an error
9. echo $lang;
10. ?>
Output:
Web development language: PHP
Notice: Undefined variable: lang in D:\xampp\htdocs\program\p3.php on line 28
Global variable
The global variables are the variables that are declared outside the function. These variables can
be accessed anywhere in the program. To access the global variable within a function, use the
GLOBAL keyword before the variable. However, these variables can be directly accessed or used
outside the function without any keyword. Therefore there is no need to use any keyword to
access a global variable outside the function.
Let's understand the global variables with the help of an example:
Example:
File: global_variable1.php
1. <?php
2. $name = "Sanaya Sharma"; //Global Variable
3. function global_var()
4. {
5. global $name;
6. echo "Variable inside the function: ". $name;
7. echo "</br>";
8. }
9. global_var();
10. echo "Variable outside the function: ". $name;
11. ?>
Output:
Variable inside the function: Sanaya Sharma
Variable outside the function: Sanaya Sharma
Note: Without using the global keyword, if you try to access a global variable inside the function, it
will generate an error that the variable is undefined.
Example:
File: global_variable2.php
1. <?php
2. $name = "Sanaya Sharma"; //global variable
3. function global_var()
4. {
5. echo "Variable inside the function: ". $name;
6. echo "</br>";
7. }
8. global_var();
9. ?>
Output:
Notice: Undefined variable: name in D:\xampp\htdocs\program\p3.php on line 6
Variable inside the function:
Using $GLOBALS instead of global
Another way to use the global variable inside the function is predefined $GLOBALS array.
Example:
File: global_variable3.php
1. <?php
2. $num1 = 5; //global variable
3. $num2 = 13; //global variable
4. function global_var()
5. {
6. $sum = $GLOBALS['num1'] + $GLOBALS['num2'];
7. echo "Sum of global variables is: " .$sum;
8. }
9. global_var();
10. ?>
Output:
Sum of global variables is: 18
If two variables, local and global, have the same name, then the local variable has higher priority
than the global variable inside the function.
Example:
File: global_variable2.php
1. <?php
2. $x = 5;
3. function mytest()
4. {
5. $x = 7;
6. echo "value of x: " .$x;
7. }
8. mytest();
9. ?>
Output:
Value of x: 7
Note: local variable has higher priority than the global variable.
Static variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed.
Sometimes we need to store a variable even after completion of function execution. Therefore,
another important feature of variable scoping is static variable. We use the static keyword before
the variable to define a variable, and this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program
execution leaves the scope. Understand it with the help of an example:
Example:
File: static_variable.php
1. <?php
2. function static_var()
3. {
4. static $num1 = 3; //static variable
5. $num2 = 6; //Non-static variable
6. //increment in non-static variable
7. $num1++;
8. //increment in static variable
9. $num2++;
10. echo "Static: " .$num1 ."</br>";
11. echo "Non-static: " .$num2 ."</br>";
12. }
13.
14. //first function call
15. static_var();
16.
17. //second function call
18. static_var();
19. ?>
Output:
Static: 4
Non-static: 7
Static: 5
Non-static: 7
You have to notice that $num1 regularly increments after each function call, whereas $num2 does
not. This is why because $num1 is not a static variable, so it freed its memory after the execution
of each function call.
PHP $ and $$ Variables
The $var (single dollar) is a normal variable with the name var that stores any value like string,
integer, float, etc.
The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.
To understand the difference better, let's see some examples.
Example 1
1. <?php
2. $x = "abc";
3. $$x = 200;
4. echo $x."<br/>";
5. echo $$x."<br/>";
6. echo $abc;
7. ?>
Output:
In the above example, we have assigned a value to the variable x as abc. Value of reference
variable $$x is assigned as 200.
Now we have printed the values $x, $$x and $abc.
Example2
1. <?php
2. $x="U.P";
3. $$x="Lucknow";
4. echo $x. "<br>";
5. echo $$x. "<br>";
6. echo "Capital of $x is " . $$x;
7. ?>
Output:
In the above example, we have assigned a value to the variable x as U.P. Value of reference
variable $$x is assigned as Lucknow.
Now we have printed the values $x, $$x and a string.
Example3
1. <?php
2. $name="Cat";
3. ${$name}="Dog";
4. ${${$name}}="Monkey";
5. echo $name. "<br>";
6. echo ${$name}. "<br>";
7. echo $Cat. "<br>";
8. echo ${${$name}}. "<br>";
9. echo $Dog. "<br>";
10. ?>
Output:
In the above example, we have assigned a value to the variable name Cat. Value of reference
variable ${$name} is assigned as Dog and ${${$name}} as Monkey.
Now we have printed the values as $name, ${$name}, $Cat, ${${$name}} and $Dog.
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the script
except for magic constants, which are not really constants. PHP constants can be defined by 2
ways:
1. define(name, value, case-insensitive)
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>
Output:
Hello JavaTpoint PHP
Create a constant with case-insensitive name:
File: constant2.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE, "</br>";
4. echo message;
5. ?>
Output:
Hello JavaTpoint PHP
Hello JavaTpoint PHP
File: constant3.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>
Output:
Hello JavaTpoint PHP
Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message
PHP constant: const keyword
PHP introduced a keyword const to create a constant. The const keyword defines constants at
compile time. It is a language construct, not a function. The constant defined using const keyword
are case-sensitive.
File: constant4.php
1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>
Output:
Hello const by JavaTpoint PHP
Constant() function
There is another way to print the value of constants using constant() function instead of using the
echo statement.
Syntax
The syntax for the following constant function:
1. constant (name)
File: constant5.php
1. <?php
2. define("MSG", "JavaTpoint");
3. echo MSG, "</br>";
4. echo constant("MSG");
5. //both are similar
6. ?>
Output:
JavaTpoint
JavaTpoint
Constant vs Variables
Constant Variables
Once the constant is defined, it can never be A variable can be undefined as well as
A constant can only be defined using define() A variable can be defined by simple
assignment.
There is no need to use the dollar ($) sign To declare a variable, always use the
before constant during the assignment. dollar ($) sign before the variable.
Constants do not follow any variable scoping Variables can be declared anywhere in
rules, and they can be defined and accessed the program, but they follow variable
Constants are the variables whose values can't The value of the variable can be changed.
Magic Constants
Magic constants are the predefined constants in PHP which get changed on the basis of their use.
They start with double underscore (__) and ends with double underscore.
They are similar to other predefined constants but as they change their values with the context,
they are called magic constants.
There are nine magic constants in PHP. In which eight magic constants start and end with double
underscores (__).
1. __LINE__
2. __FILE__
3. __DIR__
4. __FUNCTION__
5. __CLASS__
6. __TRAIT__
7. __METHOD__
8. __NAMESPACE__
9. ClassName::class
All of the constants are resolved at compile-time instead of run time, unlike the regular constant.
Magic constants are case-insensitive.
Changelog
Versio Description
n
1. <?php
2. echo "<h3>Example for __LINE__</h3>";
3. // print Your current line number i.e;4
4. echo "You are at line number " . __LINE__ . "<br><br>";
5. ?>
Output:
Example for __LINE__
1. <?php
2. echo "<h3>Example for __FILE__</h3>";
3. //print full path of file with .php extension
4. echo __FILE__ . "<br><br>";
5. ?>
Output:
Example for __FILE__
D:\xampp\htdocs\program\magic.php
3. __DIR__:
It returns the full directory path of the executed file. The path returned by this magic constant is
equivalent to dirname(__FILE__). This magic constant does not have a trailing slash unless it is a
root directory.
Example:
1. <?php
2. echo "<h3>Example for __DIR__</h3>";
3. //print full path of directory where script will be placed
4. echo __DIR__ . "<br><br>";
5. //below output will equivalent to above one.
6. echo dirname(__FILE__) . "<br><br>";
7. ?>
Output:
Example for __DIR__
D:\xampp\htdocs\program
D:\xampp\htdocs\program
4. __FUNCTION__:
This magic constant returns the function name, where this constant is used. It will return blank if it
is used outside of any function.
Example:
1. <?php
2. echo "<h3>Example for __FUNCTION__</h3>";
3. //Using magic constant inside function.
4. function test(){
5. //print the function name i.e; test.
6. echo 'The function name is '. __FUNCTION__ . "<br><br>";
7. }
8. test();
9.
10. //Magic constant used outside function gives the blank output.
11. function test_function(){
12. echo 'Hie';
13. }
14. test_function();
15. //give the blank output.
16. echo __FUNCTION__ . "<br><br>";
17. ?>
Output:
Example for __FUNCTION__
The function name is test
Hie
5. __CLASS__:
It returns the class name, where this magic constant is used. __CLASS__ constant also works in
traits.
Example:
1. <?php
2. echo "<h3>Example for __CLASS__</h3>";
3. class JTP
4. {
5. public function __construct() {
6. ;
7. }
8. function getClassName(){
9. //print name of the class JTP.
10. echo __CLASS__ . "<br><br>";
11. }
12. }
13. $t = new JTP;
14. $t->getClassName();
15.
16. //in case of multiple classes
17. class base
18. {
19. function test_first(){
20. //will always print parent class which is base here.
21. echo __CLASS__;
22. }
23. }
24. class child extends base
25. {
26. public function __construct() {
27. ;
28. }
29. }
30. $t = new child;
31. $t->test_first();
32. ?>
Output:
Example for __CLASS__
JTP
base
6. __TRAIT__:
This magic constant returns the trait name, where it is used.
Example:
1. <?php
2. echo "<h3>Example for __TRAIT__</h3>";
3. trait created_trait {
4. function jtp(){
5. //will print name of the trait i.e; created_trait
6. echo __TRAIT__;
7. }
8. }
9. class Company {
10. use created_trait;
11. }
12. $a = new Company;
13. $a->jtp();
14. ?>
Output:
Example for __TRAIT__
created_trait
7. __METHOD__:
It returns the name of the class method where this magic constant is included. The method name
is returned the same as it was declared.
Example:
1. <?php
2. echo "<h3>Example for __METHOD__</h3>";
3. class method {
4. public function __construct() {
5. //print method::__construct
6. echo __METHOD__ . "<br><br>";
7. }
8. public function meth_fun(){
9. //print method::meth_fun
10. echo __METHOD__;
11. }
12. }
13. $a = new method;
14. $a->meth_fun();
15. ?>
Output:
Example for __METHOD__
method:: construct
method:: meth_fun
8. __NAMESPACE__:
It returns the current namespace where it is used.
Example:
1. <?php
2. echo "<h3>Example for __NAMESPACE__</h3>";
3. class name {
4. public function __construct() {
5. echo 'This line will print on calling namespace.';
6. }
7. }
8. $class_name = __NAMESPACE__ . '\name';
9. $a = new class_name;
10. ?>
Output:
Example for __NAMESPACE__
1. <?php
2. namespace Technical_Portal;
3. echo "<h3>Example for CLASSNAME::CLASS </h3>";
4. class javatpoint {
5. }
6. echo javatpoint::class; //ClassName::class
7. ?>
Output:
Example for ClassName::class
Technical_Portal\javatpoint
Note: Remember namespace must be the very first statement or after any declare call in the script,
otherwise it will generate Fatal error.
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:
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
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE
(0). It is often used with conditional statements. If the condition is correct, it returns TRUE
otherwise FALSE.
Example:
1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>
Output:
This condition is TRUE.
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.
Rules for integer:
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31
to 2^31.
Example:
1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with
a fractional or decimal point, including a negative or positive sign.
Example:
1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:
Addition of floating numbers: 73.812
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.
String values must be enclosed either within single quotes or in double quotes. But both are
treated differently. To clarify this, see the example below:
Example:
1. <?php
2. $company = "Javatpoint";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
6. echo 'Hello $company';
7. ?>
Output:
Hello Javatpoint
Hello $company
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single
variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and values
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
You will learn more about array in later chapters of this tutorial.
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They
must be explicitly declared.
Example:
1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:
Bike Model: Royal Enfield
This is an advanced topic of PHP, which we will discuss later in detail.
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls
or references to external PHP resources. For example - a database call. It is an external resource.
This is an advanced topic of PHP, so we will discuss it later in detail with examples.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in
capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
1. <?php
2. $nl = NULL;
3. echo $nl; //it will not give any output
4. ?>
Output:
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators
are used to perform operations on variables or values. For example:
1. $num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
PHP Operators can be categorized in following forms:
o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators
o Execution Operators
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as
addition, subtraction, etc. with numeric values.
$b
The exponentiation (**) operator has been introduced in PHP 5.6.
Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment
operator is "=".
$b
Assign $b
Assign $b
(quotient)
Assign $b
(remainder)
Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.
& And $a & $b Bits that are 1 in both $a and $b are set to
1, otherwise 0.
or)
or)
~ Not ~$a Bits that are 1 set to 0 and bits that are 0
are set to 1
<< Shift left $a << Left shift the bits of operand $a $b steps
$b
$b number of places
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of
comparison operators are given:
$b
!== Not identical $a !== Return TRUE if $a is not equal to $b, and
$b
$b
equal to $b
>= Greater than or $a >= Return TRUE if $a is greater than or equal
equal to $b $b
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.
Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow
the evaluation and manipulation of specific bits within the integer.
d $b
xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
! Not ! $a Return TRUE if $a is not true
String Operators
The string operators are used to perform the operation on strings. There are two string operators
in PHP, which are given below:
e.g. $a = $a . $b
Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the
values of arrays.
$b pair
Identity $b
$b
Type Operators
The type operator instanceof is used to determine whether an object, its parent and its derived
class are the same type or not. Basically, this operator determines which certain class the object
belongs to. It is used in object-oriented programming.
1. <?php
2. //class declaration
3. class Developer
4. {}
5. class Programmer
6. {}
7. //creating an object of type Developer
8. $charu = new Developer();
9.
10. //testing the type of object
11. if( $charu instanceof Developer)
12. {
13. echo "Charu is a developer.";
14. }
15. else
16. {
17. echo "Charu is a programmer.";
18. }
19. echo "</br>";
20. var_dump($charu instanceof Developer); //It will return true.
21. var_dump($charu instanceof Programmer); //It will return false.
22. ?>
Output:
Charu is a developer.
bool(true) bool(false)
Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell
command. Execution operator and shell_exec() give the same result.
`dir`; result.
current folder.
Note: Note that backticks (``) are not single-quotes.
associative
[ array() left
** arithmetic right
associative
concatenation
associative
associative
| bitwise OR left
|| logical OR left
?: ternary left
>>= =>
or logical left
PHP Comments
PHP comments can be used to describe any line of code so that other developer can understand
the code easily. It can also be used to hide any code.
PHP supports single line and multi line comments. These comments are similar to C/C++ and Perl
style (Unix shell style) comments.
PHP Single Line Comments
There are two ways to use single line comments in PHP.
1. <?php
2. // this is C++ style single line comment
3. # this is Unix Shell style single line comment
4. echo "Welcome to PHP single line comments";
5. ?>
Output:
Welcome to PHP single line comments
PHP Multi Line Comments
In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */.
Let's see a simple example of PHP multiple line comment.
1. <?php
2. /*
3. Anything placed
4. within comment
5. will not be displayed
6. on the browser;
7. */
8. echo "Welcome to PHP multi line comment";
9. ?>
Output:
Welcome to PHP multi line comment