0% found this document useful (0 votes)
4 views56 pages

PHP Nontes

The document outlines a PHP programming module (SWDPP401) that covers the basics of PHP, including its definition, features, syntax, and variable management. It explains how PHP is a server-side scripting language used for web development, highlighting its capabilities and installation methods. Additionally, it covers PHP syntax, case sensitivity, comments, and the use of echo and print statements for outputting data.

Uploaded by

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

PHP Nontes

The document outlines a PHP programming module (SWDPP401) that covers the basics of PHP, including its definition, features, syntax, and variable management. It explains how PHP is a server-side scripting language used for web development, highlighting its capabilities and installation methods. Additionally, it covers PHP syntax, case sensitivity, comments, and the use of echo and print statements for outputting data.

Uploaded by

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

MODULE_CODE: SWDPP401

MODULE_NAME: PHP PROGRAMMING


Credits: 13
Learning Hours: 130

Theoretical content 30%


Practical work:
Group project and presentation 20%
Individual project /Work 50%
What is PHP?
PHP is an open source, interpreted and object-oriented scripting language i.e. executed at
server side. It is used to develop web applications

 PHP is an acronym(Stands) for "PHP: Hypertext Preprocessor"


 PHP is a widely-used, open source scripting language
 PHP is a server-side scripting language.
 PHP is faster than other scripting languages, for example, ASP and JSP.
 PHP is free to download and use

PHP is an amazing and popular language!

It is powerful enough to be at the core of the biggest blogging system on the


web (WordPress)!
It is deep enough to run the largest social network (Facebook)!
It is also easy enough to be a beginner's first server-side language!

What is a PHP File?


 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the
browser as plain HTML
 PHP files have extension ".php"

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

With PHP you are not limited to output HTML. You can output images, PDF files,
and even Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side

#PHP Features
There are given many features of PHP.

o Performance: Script written in PHP executes much faster than those scripts written
in other languages such as JSP & ASP.
o Open Source Software: PHP source code is free available on the web; you can
develop all the version of PHP according to your requirement without paying any
cost.
o Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX
operating system. A PHP application developed in one OS can be easily executed in
other OS also.
o Compatibility: PHP is compatible with almost all local servers used today like
Apache, IIS etc.
o Embedded: PHP code can be easily embedded within HTML tags and script.

Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems. There are many AMP options available in the market that
are given below:

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
components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail etc.

If you are on Windows and don't want Perl and other features of XAMPP, you should go for
WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.
PHP 5 Syntax
A PHP script is executed on the server, and the plain HTML result is sent back
to the browser.

Basic PHP Syntax


A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php
// PHP code goes here
?>

The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

Note: PHP statements end with a semicolon (;).


Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the
program. Its only purpose is to be read by someone who is looking at the code.

Comments can be used to:

 Let others understand what you are doing


 Remind yourself of what you did - Most programmers have experienced
coming back to their own work a year or two later and having to re-figure
out what they did. Comments can remind you of what you were thinking
when you wrote the code

PHP supports several ways of commenting:

Example
<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment

/*
This is a multiple-lines comment block
that spans over multiple
lines
*/

// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>

</body>
</html>
PHP Case Sensitivity
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are NOT case-sensitive.

In the example below, all three echo statements below are legal (and equal):

Example
<!DOCTYPE html>
<html>
<body>

<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

</body>
</html>

However; all variable names are case-sensitive.

In the example below, only the first statement will display the value of the
$color variable (this is because $color, $COLOR, and $coLOR are treated as
three different variables):

Example
<!DOCTYPE html>
<html>
<body>

<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

</body>
</html>

PHP echo and print Statements


echo and print are more or less the same. They are both used to output data to
the screen.

The differences are small: echo has no return value while print has a return
value of 1 so it can be used in expressions. echo can take multiple parameters
(although such usage is rare) while print can take one argument. echo is
marginally faster than print.

PHP Echo
PHP echo is a language construct not a function, so you don't need to use parenthesis with
it. But if you want to use more than one parameters, it is required to use parenthesis.

The syntax of PHP echo is given below:

1. void echo (string $arg1 [, string $...])

PHP echo statement can be used to print string, multi line strings, escaping characters,
variable, array etc.

PHP echo: printing string


File: echo1.php

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


1. <?php
2. echo "Hello escape \"sequence\" characters";
3. ?>

Output:

Hello escape "sequence" characters

PHP echo: printing variable value


1. <?php
2. $msg="Hello PHP Developers";
3. echo "Message is: $msg";
4. ?>

Output:

Message is: Hello PHP Developers

PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with
the argument list. 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 string, multi line strings, escaping characters,
variable, array etc.

PHP print: printing string


File: print1.php

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 Variables
A variable in PHP is a name of memory location that holds data. A variable is a temporary
storage that is used to store data temporarily.

In PHP, a variable is declared using $ sign followed by variable name.

Syntax of declaring a variable in PHP is given below:

Syntax of declaring PHP Variables


$variablename=value;

PHP Variables
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two different
variables)

Output Variables
The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>

The following example will produce the same output as the example above:
Example
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>

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

Sum of two variables


File: variable2.php
1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>
PHP Variable: case sensitive
In PHP, variable names are case sensitive. So variable name "color" is different from Color,
COLOR, COLor etc.#

Remember that PHP variable names are case-sensitive!

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. ?>

7. <?php
8. $4c="hello";//number (invalid)
9. $*d="hello";//special symbol (invalid)
10.
11. echo "$4c <br/> $*d";
12. ?>

PHP is a Loosely Typed Language


In the example above, notice that we did not have to tell PHP which data type
the variable is.

PHP automatically converts the variable to the correct data type, depending on
its value.

In other languages such as C, C++, and Java, the programmer must declare the
name and type of the variable before using it.

PHP Variables Scope


In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be
referenced/used.
PHP has three different variable scopes:

 local
 global
 static

Global and Local Scope


A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:

Example
<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>

A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:

Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared.
PHP The global Keyword
The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

Example
<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the
variable. This array is also accessible from within functions and can be used to update global variables
directly.

The example above can be rewritten like this:

Example
<?php
$x = 5;
$y = 10;

function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15
?>
PHP The Static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:

Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>

Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.

Note: The variable is still local to the function.

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; ?>
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. ?>

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. PHP constants can be defined by 2 ways:

1. Using define () function


2. Using const keyword

PHP constants follow the same PHP variable rules. For example, it can be started with
letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()


Let's see the syntax of define() function in PHP.

1. define(name, value, case-insensitive)


1. name: specifies the constant name
2. value: specifies the constant value
3. case-insensitive: Default value is false. It means it is case sensitive by default.

Let's see the example to define PHP constant using define().

File: constant1.php

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>

Output:

Hello JavaTpoint PHP


File: constant2.php

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE;
4. echo message; ?>
Output:

Hello JavaTpoint PHPHello 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


The const keyword defines constants at compile time. It is a language construct not a
function.

It is bit faster than define().

It is always 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


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 eight magical constants defined in the below table. They are case-insensitive.

Name Description

__LINE__ Represents current line number where it is used.

__FILE__ Represents full path and file name of the file. If it is used inside an include,
name of included file is returned.

__DIR__ Represents full directory path of the file. Equivalent to dirname(__file__). It


does not have a trailing slash unless it is a root directory. It also resolves
symbolic link.

__FUNCTION__ Represents the function name where it is used. If it is used outside of any
function, then it will return blank.

__CLASS__ Represents the class name where it is used. If it is used outside of any
function, then it will return blank.

__TRAIT__ Represents the trait name where it is used. If it is used outside of any
function, then it will return blank. It includes namespace it was declared in.

__METHOD__ Represents the name of the class method where it is used. The method
name is returned as it was declared.

__NAMESPACE__ Represents the name of the current namespace.


Example
Let's see an example for each of the above magical constants.

File Name: magic.php

1. <?php
2. echo "<h3>Example for __LINE__</h3>";
3. echo "You are at line number " . __LINE__ . "<br><br>";// print Your current line number i.e;
3
4. echo "<h3>Example for __FILE__</h3>";
5. echo __FILE__ . "<br><br>";//print full path of file with .php extension
6. echo "<h3>Example for __DIR__</h3>";
7. echo __DIR__ . "<br><br>";//print full path of directory where script will be placed
8. echo dirname(__FILE__) . "<br><br>"; //its output is equivalent to above one.
9. echo "<h3>Example for __FUNCTION__</h3>";
10. //Using magic constant inside function.
11. function cash(){
12. echo 'the function name is '. __FUNCTION__ . "<br><br>";//the function name is cash.
13. }
14. cash();
15. //Using magic constant outside function gives the blank output.
16. function test_function(){
17. echo 'HYIIII';
18. }
19. test_function();
20. echo __FUNCTION__ . "<br><br>";//gives the blank output.
21.
22. echo "<h3>Example for __CLASS__</h3>";
23. class abc
24. {
25. public function __construct() {
26. ;
27. }
28. function abc_method(){
29. echo __CLASS__ . "<br><br>";//print name of the class abc.
30. }
31. }
32. $t = new abc;
33. $t->abc_method();
34. class first{
35. function test_first(){
36. echo __CLASS__;//will always print parent class which is first here.
37. }
38. }
39. class second extends first
40. {
41. public function __construct() {
42. ;
43. }
44. }
45. $t = new second;
46. $t->test_first();
47. echo "<h3>Example for __TRAIT__</h3>";
48. trait created_trait{
49. function abc(){
50. echo __TRAIT__;//will print name of the trait created_trait
51. }
52. }
53. class anew{
54. use created_trait;
55. }
56. $a = new anew;
57. $a->abc();
58. echo "<h3>Example for __METHOD__</h3>";
59. class meth{
60. public function __construct() {
61. echo __METHOD__ . "<br><br>";//print meth::__construct
62. }
63. public function meth_fun(){
64. echo __METHOD__;//print meth::meth_fun
65. }
66. }
67. $a = new meth;
68. $a->meth_fun();
69.
70. echo "<h3>Example for __NAMESPACE__</h3>";
71. class name{
72. public function __construct() {
73. echo 'This line will be printed on calling namespace';
74. }
75. }
76. $clas_name= __NAMESPACE__ .'\name';
77. $a = new $clas_name; ?>

PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. 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 Comparison Operators
o Bitwise Operators
o Logical Operators
o String Operators
o Incrementing/Decrementing Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators
o Assignment Operators

We can also categorize operators on behalf of operands. They can be categorized in 3 forms:

o Unary Operators: works on single operands such as ++, -- etc.


o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

PHP Operators Precedence


o Let's see the precedence of PHP operators with associativity.

Operators Additional Information Associativity

clone new clone and new non-


associative
[ array() left

** arithmetic right

++ -- ~ (int) (float) (string) (array) increment/decrement and right


(object) (bool) @ types

instanceof types non-


associative

! logical (negation) right

*/% arithmetic left

+-. arithmetic and string left


concatenation

<< >> bitwise (shift) left

< <= > >= comparison non-


associative

== != === !== <> comparison non-


associative

& bitwise AND left

^ bitwise XOR left

| bitwise OR left

&& logical AND left

|| logical OR left

?: ternary left

= += -= *= **= /= .= %= &= |= ^= assignment right


<<= >>= =>

and logical left


xor logical left

or logical left

, many uses (comma) left

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
2. Compound Types
3. Special Types

PHP Data Types: Scalar Types


There are 4 scalar data types in PHP.

1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types


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
Boolean
These data types provide output as 0 or 1. In PHP, value of True is one and the value of
False is nothing.

Syntax
1. <?php
2. $foo = True; // assign the value TRUE to $foo
3. ?>

Example 1
1. <?php
2. $a=true;
3. echo $a;
4. ?>

PHP is_bool() function


By using this function, we can check whether the variable is boolean variable or not.

Syntax
1. bool is_bool ( mixed $var )

It return True if var is boolean, False otherwise.

Example 1
1. <?php
2. $x=false;
3. echo is_bool($x);
4. ?>

Example 2
1. <?php
2. $y=false;
3. if (is_bool($y))
4. echo 'This is a boolean type.';
5. else
6. echo 'This is not a boolean type.';
7. ?>

Integer
This data type holds only numeric values. It stores only whole number with no
fractional component. The range of integers must lie between -2^31 to 2^31.

Syntax
Integers can be defined in decimal(base 10), hexadecimal(base 16), octal(base 8) or
binary(base 2) notation.

Example 1
1. <?php
2. $x=123;
3. echo $x;
4. ?>

Output:

Example 2
1. <?php
2. $a=100;
3. var_dump($a);
4. ?>

Output:

Example 3
1. <?php
2. // decimal base integers
3. $deci1 = 40;
4. $deci2 = 500;
5. // octal base integers
6. $octal1 = 07;
7. // hexadecimal base integers
8. $octal = 0x45;
9. $add = $deci1 + $deci2;
10. echo $add;
11. ?>

PHP is_int() function


By using this function, we can check the input variable is integer or not. This function
was introduced in PHP 4.0.

Syntax
1. bool is_int (mixed $var)

This function returns true if var_name is an integer, Otherwise false.

Example 1
1. <?php
2. $x=123;
3. echo is_int($x);
4. ?>
Example 2
1. <?php
2. $x = 56;
3. $y = "xyz";
4.
5. if (is_int($x))
6. {
7. echo "$x is Integer \n" ;
8. }
9. else
10. {
11. echo "$x is not an Integer \n" ;
12. }
13. if (is_int($y))
14. {
15. echo "$y is Integer \n" ;
16. }
17. else
18. {
19. echo "$y is not Integer \n" ;
20. }
21. ?>
Example 3
1. <?php
2.
3. $check = 12345;
4. if( is_int($check ))
5. {
6. echo $check . " is an int!";
7. }
8. else
9. {
10. echo $check . " is not an int!";
11. }
12. ?>
Float
This data type represents decimal values. The float (floating point number) is a
number with a decimal point or a number in exponential form.

Syntax
1. $a=1.234;
2. $x=1.2e4;
3. $y=7E-10;
Example 1
1. <?php
2. $x=22.41;
3. echo $x;
4. ?>
Example 2
1. <?php
2. $a = 11.365;
3. var_dump($a);
4. ?>
Example 3
1. <?php
2. $a = 6.203;
3. $b = 2.3e4;
4. $c = 7E-10;
5. var_dump($a);
6. var_dump($b);
7. var_dump($c);
8. ?>
PHP is_float Function
By using this function, we can check that the input value is float or not. This function
was introduced in PHP 4.0.

Syntax
1. bool is_float ( mixed $var )

The is_float() function returns TRUE if the var_name is float, otherwise false.

Example 1
1. <?php
2. $x=123.41;
3. echo is_float($x); ?>
Example 2
1. <?php
2. $a=123.41;
3. $b=12;
4. var_dump (is_float($a));
5. var_dump (is_float($b));
6. ?>

Output:

Example 3
1. <?php
2. $var_name=126.56;
3. if (is_float($var_name))
4. echo 'This is a float value.<br>';
5. else
6. echo 'This is not a float value.<br>';
7. var_dump(is_float('javatpoint'));
8. echo '<br>';
9. var_dump(is_float(85));
10. ?>
Precision:
It is a configuration setting in php.ini used to specify a total number of digits
displayed in floating point number.
Compound Types
There are 2 compound data types in PHP.

1. Array
2. Object

Array:
The array is a collection of heterogeneous (dissimilar) data types. PHP is a loosely typed
language that?s why we can store any type of values in arrays.

Normal variable can store single value, array can store multiple values.The array contains
a number of elements, and each element is a combination of element key and element
value.

SYNTAX OF ARRAY DECLARATION:


1. Variable_name = array (element1, element2, element3, element4......)

Example 1
1. <?php
2. $arr= array(10,20,30);
3. print_r($arr);
4. ?>

Example 2
1. <?php
2. $arr= array(10,'sonoo',30);
3. print_r($arr);
4. ?>

Example 3
1. <?php
2. $arr= array(0=>10,2=>'sonoo',3=>30);
3. print_r($arr);
4. ?>

Object:
An object is a data type which accumulates data and information on how to process that
data. An object is a specific instance of a class which delivers as templates for objects.

SYNTAX:

At first, we must declare a class of object. A class is a structure which consists of


properties and methods. Classes are specified with the class keyword. We specify the
data type in the object class, and then we use the data type in instances of that class.

Example 1
1. <?php class vehicle
2. {
3. function car()
4. {
5. echo "Display tata motors";
6. }
7. }
8. $obj1 = new vehicle;
9. $obj1->car();
10. ?>

Example 2
1. <?php
2. class student
3. {
4. function student()
5. {
6. $this->kundan = 100;
7. }
8. }
9. $obj = new student();
10. echo $obj->kundan;
11. ?>

Example 3
1. <?php
2. class greeting
3. {
4. public $str = "Hello javatpoint and SSSIT";
5. function show_greeting()
6. {
7. return $this->str;
8. }
9. }
10. $obj = new greeting;
11. var_dump($obj);
12. ?>

Special Types
There are 2 special data types in PHP

1. Resource
2. Null

Resource Data type:


It refers the external resources like database connection, FTP connection, file pointers, etc.
In simple terms, a resource is a special variable which carrying a reference to an external
resource.
Example 1
1. <?php
2. $conn = ftp_connect("127.0.0.1") or die("Could not connect");
3. echo get_resource_type($conn);
4. ?>

Example 2
1. <?php
2. $conn= ftp_connect("127.0.0.1") or die("could not connect");
3. echo $conn;
4. ?>

Example 3
1. <?php
2. $handle = fopen("tpoint.txt", "r");
3. var_dump($handle);
4. echo "<br>";
5. $conn= ftp_connect("127.0.0.1") or die("could not connect");
6. var_dump($conn);
7. ?>

Null Data Type:


A variable of type Null is a variable without any data. In PHP, null is not a value, and we can
consider it as a null variable based on 3 condition.

1. If the variable is not set with any value.


2. If the variable is set with a null value.
3. If the value of the variable is unset.
Example 1
1. <?php
2.
3. $empty=null;
4. var_dump($empty);
5. ?>

Example 2
1. <?php
2. $a1 = " ";
3. var_dump($a1);
4. echo "<br />";
5. $a2 = null;
6. var_dump($a2);
7. ?>

Example 3
1. <?php
2. $x = NULL;
3. var_dump($x);
4. echo "<br>";
5. $y = "Hello javatpoint!";
6. $y = NULL;
7. var_dump($y);
8. ?>
PHP is_null() function
By using the is_null function, we can check whether the variable is NULL or not. This function was introduced in
4.0.4.

SYNATX:
1. bool is_null ( mixed $var )

The PHP is_null() function returns true if var is null, otherwise false.

Important Note:

We can unset the variable value by using the unset function.

Example 1
1. <?php
2. $var1 = TRUE;
3. if (is_null($var1))
4. {
5. echo 'Variable is NULL';
6. }
7. else
8. {
9. echo 'Variable is not NULL';
10. }
11. ?>

Example 2
1. <?php
2. $x= 100;
3. unset($x);
4. echo is_null($x);
5. ?>
Example 3
1. <?php
2. $x = NULL;
3. $y = "\0";
4. is_null($x) ? print_r("True\n") : print_r("False\n");
5. echo "<br/>";
6. is_null($y) ? print_r("True\n") : print_r("False\n");
7. ?>

Control Statement

PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement in
PHP.

o if
o if-else
o if-else-if
o nested if

PHP If Statement
PHP if statement is executed if condition is true.

Syntax

1. if(condition){
2. //code to be executed
3. }

Example

1. <?php
2. $num=12;
3. if($num<100){
4. echo "$num is less than 100";
5. }
6. ?>
Output: 12 is less than 100

PHP If-else Statement


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

Syntax

1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }

Example

1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>

Output: 12 is even number

PHP - The if...elseif....else Statement


The if....elseif...else statement executes different codes for more than two
conditions.

Syntax
if (condition) {
//code to be executed if this condition is true;
} elseif (condition) {
//code to be executed if this condition is true;
} else {
//code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less
than 10, and "Have a good day!" if the current time is less than 20. Otherwise it
will output "Have a good night!":

Example
<?php
$t = date("H");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works
like PHP if-else-if statement.

Use the switch statement to select one of many blocks of code to be


executed

Syntax

1. switch(expression){
2. case value1:
3. //code to be executed
4. break;
5. case value2:
6. //code to be executed
7. break;
8. ......
9. default:
10. code to be executed if all cases are not matched;
11. }

PHP Switch Example

1. <?php
2. $num=20;
3. switch($num){
4. case 10:
5. echo("number is equals to 10");
6. break;
7. case 20:
8. echo("number is equal to 20");
9. break;
10. case 30:
11. echo("number is equal to 30");
12. break;
13. default:
14. echo("number is not equal to 10, 20 or 30");
15. }
16. ?>

Output:

number is equal to 20

Ex2.
1. <?php
2. $ch = "B.Tech";
3. switch ($ch)
4. {
5. case "BCA":
6. echo "BCA is 3 years course";
7. break;
8. case "Bsc":
9. echo "Bsc is 3 years course";
10. break;
11. case "B.Tech":
12. echo "B.Tech is 4 years course";
13. break;
14. case "B.Arch":
15. echo "B.Arch is 5 years course";
16. break;
17. default:
18. echo "Wrong Choice";
19. break;
20. }
21. ?>
Important points to be noticed about switch case:
1. The default is an optional statement. Even it is not important, that default
must always be the last statement.
2. There can be only one default in a switch statement. More than one default
may lead to a Fatal error.
3. Each case can have a break statement, which is used to terminate the
sequence of statement.
4. The break statement is optional to use in switch. If break is not used, all the
statements will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in
switch expression.
6. Nesting of switch statements is allowed, but it makes the program more
complex and less readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.

PHP For Loop


PHP for loop can be used to traverse set of code for the specified number of times.

It should be used if number of iteration is known otherwise use while loop.

Syntax

1. for(initialization; condition; increment/decrement){


2. //code to be executed
3. }

Example

1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?> Output:
1
2
3
4
5
6
7
8
9
10

PHP Nested For Loop


We can use for loop inside for loop in PHP, it is known as nested for loop.

In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If
outer for loop is to be executed for 3 times and inner for loop for 3 times, inner for loop will
be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for
3rd outer loop).

Example

1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. }
6. }
7. ?>

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
PHP For Each Loop
PHP for each loop is used to traverse array elements.

Syntax

1. foreach( $array as $var ){


2. //code to be executed
3. }
4. ?>

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>

Output:

Season is: summer


Season is: winter
Season is: spring
Season is: autumn

PHP Break
PHP break statement breaks the execution of current for, while, do-while, switch and for-
each loop. If you use break inside inner loop, it breaks the execution of inner loop only.

Syntax

1. jump statement;
2. break;

PHP Break: inside loop


Let's see a simple example to break the execution of for loop if value of i is equal to 5.

1. <?php
2. for($i=1;$i<=10;$i++){
3. echo "$i <br/>";
4. if($i==5){
5. break;
6. }
7. }
8. ?>

Output:

1
2
3
4
5

PHP Break: inside inner loop


The PHP break statement breaks the execution of inner loop only.

1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. if($i==2 && $j==2){
6. break;
7. }
8. }
9. }
10. ?>

Output:

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
PHP continue statement
The PHP continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition.

The continue statement is used within looping and switch control structure
when you immediately jump to the next iteration.

The continue statement can be used with all types of loops such as - for,
while, do-while, and foreach loop. The continue statement allows the user to
skip the execution of the code for the specified condition.

Syntax
1. //jump-statement;
2. continue;

PHP While Loop


PHP while loop can be used to traverse set of code like for loop.

It should be used if number of iteration is not known.

Syntax

1. while(condition){
2. //code to be executed
3. }

Alternative Syntax

1. while(condition):
2. //code to be executed
3. endwhile;

PHP While Loop Example

1. <?php
2. $n=1;
3. while($n<=10){
4. echo "$n<br/>";
5. $n++;
6. }
7. ?>

Output:

1
2
3
4
5
6
7
8
9
10

Alternative Example

1. <?php
2. $n=1;
3. while($n<=10):
4. echo "$n<br/>";
5. $n++;
6. endwhile;
7. ?>

Output:

1
2
3
4
5
6
7
8
9
10
PHP Nested While Loop
We can use while loop inside another while loop in PHP, it is known as nested while loop.

In case of inner or nested while loop, nested while loop is executed fully for one outer while
loop. If outer while loop is to be executed for 3 times and nested while loop for 3 times,
nested while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer
loop and 3 times for 3rd outer loop).

Example

1. <?php
2. $i=1;
3. while($i<=3){
4. $j=1;
5. while($j<=3){
6. echo "$i $j<br/>";
7. $j++;
8. }
9. $i++;
10. }
11. ?>

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP do while loop


PHP do while loop can be used to traverse set of code like php while loop. The PHP do-while
loop is guaranteed to run at least once.

It executes the code at least one time always because condition is checked after executing
the code.

Syntax
1. do{
2. //code to be executed
3. }while(condition);

Example

1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>

Output:

1
2
3
4
5
6
7
8
9
10

PHP Programs
PHP programs are frequently asked in the interview

1) Sum of Digits

Write a PHP program to print sum of digits.

Input: 23

Output: 5

Input: 624

Output: 12
2) Even or odd number

Input: 23

Output: odd number

Input: 12

Output: even number

3) Prime number

Write a PHP program to check prime number.

Input: 17

Output: not prime number

Input: 57

Output: prime number

4) Table of number

Write a PHP program to print table of a number.

Input: 2

Output: 2 4 6 8 10 12 14 16 18 20

Input: 5

Output: 5 10 15 20 25 30 35 40 45 50
5) Factorial

Write a PHP program to print factorial of a number.

Input: 5

Output: 120

Input: 6

Output: 720

6) Armstrong number

Write a PHP program to check armstrong number.

Input: 371

Output: armstrong

Input: 342

Output: not armstrong

7) Palindrome number

Write a PHP program to check palindrome number.

Input: 121

Output: not palindrome number

Input: 113

Output: palindrome number


8) Fibonacci Series

Write a PHP program to print fibonacci series without using recursion and
using recursion.

Input: 10

Output: 0 1 1 2 3 5 8 13 21 34

9) Reverse Number

Write a PHP program to reverse given number.

Input: 234

Output: 432

10) Reverse String

Write a PHP program to reverse given string.

Input: amit

Output: tima

11) Swap two numbers

Write a PHP program to swap two numbers with and without using third
variable.

Input: a=5 b=10

Output: a=10 b=5

12) Adding Two Numbers


Write a PHP program to add two numbers.

First Input: 10

Second Input: 20

Output: 30

13) Subtracting Two Numbers

Write a PHP program to subtract two numbers.

First Input: 50

Second Input: 10

Output: 40

14) Area of Triangle

Write a PHP program to find area of triangle.

Base Input: 10

Height Input: 15

Output: 75

15) Area of rectangle

Write a PHP program to find the area of rectangle.

Length Input: 10

Width Input: 20

Output: 200
16) Leap Year

Write a PHP program to find if the given year is leap year or not.

Input: 2000

Output: Leap Year

Input: 2001

Output: Not Leap Year

17) Alphabet Triangle using PHP method

Write a PHP program to print alphabet triangle.

Output:

A
ABA
ABCBA
ABCDCBA
ABCDEDCBA

18) Alphabet Triangle Pattern

Write a PHP program to print alphabet triangle.

Output:

A
ABA
ABCBA
ABCDCBA
ABCDEDCBA

19) Number Triangle

Write a PHP program to print number triangle.

Output:

enter the range= 6


1
121
12321
1234321
123454321
12345654321

20) Star Triangle

Write a PHP programs to print star triangle.

Output:

Output:

Output:
Output:

Output:

You might also like