Copy of Copy of PHP Programming
Copy of Copy of PHP Programming
PHP
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:
Interpreter
The PHP Interpreter is an application that executes PHP code one line at a time.
Open Source:
PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its components
are free to download and use.
Web Server
A webserver is software run by your website hosting provider so that visitors can view the
web pages on your site.
Apache
2
Apache is the most widely used webserver software and runs on 67% of all websites in the
world. Developed and maintained by Apache Software Foundation, Apache is open
source software and available for free.
It’s fast, reliable, and secure. And Apache can be highly customized to meet the needs of
many different environments by using extensions and modules.
Database
A database is information that is set up for easy access, management and updating.
DBMS
MySQL is a widely used relational database management system (RDBMS). MySQL is free
and open-source.
Static website
Static website is a web page that is delivered to the user's web browser exactly as stored,
[1]
in contrast to dynamic web pages which are generated by a web application
Dynamic website
Dynamic Website is a website containing data that can be mutable or changeable. It uses
client-side or server scripting to generate mutable content. Like a static website, it also
contains HTML data.
Purpose of PHP
PHP is a server-side scripting language, which is used to design the dynamic web
applications with MySQL database.
o It handles dynamic content, database as well as session tracking for the website.
o You can create sessions in PHP
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many
more.
o Using PHP language, you can control the user to access some pages of your website.
o PHP can handle the forms, such as - collect the data from users using forms, save it
into the database, and return useful information to the user. For example -
Registration form.
3
PHP is very popular language because of its simplicity and open source. There are some
important features of PHP given below:
Performance:
PHP script is executed much faster than those scripts which are written in other languages
such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its components
are free to download and use.
PHP has easily understandable syntax. Programmers are comfortable coding with it.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
PHP allows us to use a variable without declaring its datatype. It will be taken automatically
at the time of execution based on the type of data it contains on its value.
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft
IIS, etc.
4
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same
work in a few lines of code. It has maximum control over the websites like you can make
changes easily whenever you want.
- XAMPP WAMP/MAMP/LAMP
- IDEs /Text Editors
- Browser
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 6: XAMPP is ready to install, so click on the Next button and install the XAMPP.
5
Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run the php
program on the localhost.
6
Generally, a PHP file contains HTML tags and some PHP scripting code. It is very easy to
create a simple PHP example. To do so, create a file and write HTML tags + PHP code and
save this file with. php extension.
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
?>
Note: PHP statements end with a semicolon (;).
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:
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
PHP Variable
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some
important points to know about variables:
o As PHP is a loosely typed language, so we do not need to declare the data types of
the variables. It automatically analyzes the values and makes conversions to its
correct datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.
1. $variablename=value;
7
Rules for declaring PHP variable:
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o 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.
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:
File: variable2.php
1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>
Output:
8
11
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
File: variablevalid.php
1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4. echo "$a <br/> $_b";
5. ?>
Output:
hello
hello
File: variableinvalid.php
1. <?php
2. $4c="hello";//number (invalid)
9
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 is a loosely typed language, it means PHP automatically converts the variable to its
correct data type.
In the above example, + is the binary + operator, 10 and 20 are operands and $num is
variable.
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
10
o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as
addition, subtraction, etc. with numeric values.
Assignment Operators
The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".
11
-= Subtract then $a -= $b Subtraction same as $a = $a - $b
Assign
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.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of
places
Comparison Operators
12
Comparison operators allow comparing two values, such as number or string. Below the list
of comparison operators are given:
=== Identical $a === Return TRUE if $a is equal to $b, and they are of
$b same data type
!== Not identical $a !== Return TRUE if $a is not equal to $b, and they are
$b not of same data type
<= Less than or equal $a <= Return TRUE if $a is less than or equal $b
to $b
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a
variable.
13
Operator Name Example Explanation
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.
Xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
String Operators
The string operators are used to perform the operation on strings. There are two string
operators in PHP, which are given below:
14
or le
Array Operators
The array operators are used in case of array. Basically, these operators are used to
compare the values of arrays.
=== Identity $a === Return TRUE if $a and $b have same key/value pair of same
$b type in same order
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.
15
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. //testing the type of object
10. if( $charu instanceof Developer)
11. {
12. echo "Charu is a developer.";
13. }
14. else
15. {
16. echo "Charu is a programmer.";
17. }
18. echo "</br>";
19. var_dump($charu instanceof Developer); //It will return true.
20. var_dump($charu instanceof Programmer); //It will return false.
21. ?>
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.
`` backticks echo `dir`; Execute the shell command and return the result.
Here, it will show the directories available in current
folder.
PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an
expression, any error message will be ignored that might be generated by that expression.
16
Operator Name Example Explanation
[ array() left
** arithmetic right
17
associative
| bitwise OR left
|| logical OR left
?: ternary left
Or logical left
18
3. Special Types
It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
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:
PHP Integer
19
Integer means numeric data with a negative or positive sign. It holds only whole numbers,
i.e., numbers without fractional part or decimal points.
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:
PHP String
20
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
21
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:
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:
22
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."
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:
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;
23
10. ?>
Output:
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.
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:
1. <?php
2. $name = "Sanaya Sharma"; //global variable
3. function global_var()
4. {
5. echo "Variable inside the function: ". $name;
6. echo "</br>";
7. }
24
8. global_var();
9. ?>
Output:
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:
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. ?>
25
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
26
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 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:
Constants are similar to the variable except once they defined, they can never be undefined
or changed. They remain constant across the entire program. PHP constants follow the same
PHP variable rules. For example, it can be started with a letter or underscore only.
Note: Unlike variables, constants are automatically global throughout the script.
Use the define() function to create a constant. It defines constant at run time. Let's see the
syntax of define() function in PHP.
27
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:
File: constant2.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE, "</br>";
4. echo message;
5. ?>
Output:
File: constant3.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>
Output:
28
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:
Constant() function
There is another way to print the value of constants using constant() function instead of
using the echo statement.
Syntax
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
29
redefined. redefined easily.
A constant can only be defined using define () A variable can be defined by simple
function. It cannot be defined by any simple assignment (=) operator.
assignment.
There is no need to use the dollar ($) sign before To declare a variable, always use the dollar
constant during the assignment. ($) sign before the variable.
Constants do not follow any variable scoping Variables can be declared anywhere in the
rules, and they can be defined and accessed program, but they follow variable scoping
anywhere. rules.
Constants are the variables whose values can't be The value of the variable can be changed.
changed throughout the program.
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.
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:
30
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:
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
date(format,timestamp)
Parameter Description
timestamp Optional. Specifies a timestamp. Default is the current date and time
A timestamp is a sequence of characters, denoting the date and/or time at which a certain
event occurred.
Get a Date
31
The required format parameter of the date() function specifies how to format the date (or
time).
Here are some characters that are commonly used for dates:
Other characters, like"/", ".", or "-" can also be inserted between the characters to add
additional formatting.
Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Get a Time
Here are some characters that are commonly used for times:
The example below outputs the current time in the specified format:
Example
<?php
echo "The time is " . date("h:i:sa");
?>
The optional timestamp parameter in the date() function specifies a timestamp. If omitted,
the current date and time will be used (as in the examples above).
32
The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp
contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT)
and the time specified.
Syntax
The example below creates a date and time with the date() function from a number of
parameters in the mktime() function:
Example
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
The PHP strtotime() function is used to convert a human readable date string into a Unix
timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
Syntax
strtotime(time, now)
The example below creates a date and time from the strtotime() function:
Example
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>PHP is quite clever about converting a string to a date, so you can put in various values:
Example
<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>
33
However, strtotime() is not perfect, so remember to check the strings you put in there.
The example below outputs the dates for the next six Saturdays:
Example
<?php
$startdate = strtotime("Saturday");
$enddate = strtotime("+6 weeks", $startdate);
The example below outputs the number of days until 4th of July:
Example
<?php
$d1=strtotime("July 04");
$d2=ceil(($d1-time())/60/60/24);
echo "There are " . $d2 ." days until 4th of July.";
?>
String concatenation
Operat
Description
or
. The PHP concatenation operator (.) is used to combine two string values to create
one string.
.= Concatenation assignment.
Example:
<?php
$name="John";
$lastName="Travolta";
echo $name." ".$lastName; // Outputs John Travolta
$a="Hello";
$a .= " John!";
echo $a; // Outputs Hello John!
?>
34
condition statement
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
PHP index is represented by number which starts from 0. We can store number, string and
object in the PHP array. All PHP array elements are assigned to an index number by default.
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
35
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
File: array2.php
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>
Output:
We can associate name with each array elements in PHP using => symbol.
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
36
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>
Output:
PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if the number of iterations is known otherwise use while loop. This means
for loop is used when you already know how many times you want to execute a block of
code.
It allows users to put all the loop related statements in one place. See in the syntax given
below:
Syntax
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }
37
Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the
following meanings:
initialization - Initialize the loop counter value. The initial value of the for loop is done only
once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the
condition is false. If TRUE, the loop execution continues, otherwise the execution of the loop
ends.
Flowchart
Example
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
Output:
38
1
2
3
4
5
6
7
8
9
10
Example
All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't
pass parameters, it will execute infinite.
1. <?php
2. $i = 1;
3. //infinite loop
4. for (;;) {
5. echo $i++;
6. echo "</br>";
7. }
8. ?>
Output:
1
2
3
4
.
.
.
Example
Below is the example of printing numbers from 1 to 9 in four different ways using for loop.
1. <?php
2. /* example 1 */
3.
4. for ($i = 1; $i <= 9; $i++) {
5. echo $i;
6. }
7. echo "</br>";
8.
9. /* example 2 */
10.
11. for ($i = 1; ; $i++) {
39
12. if ($i > 9) {
13. break;
14. }
15. echo $i;
16. }
17. echo "</br>";
18.
19. /* example 3 */
20.
21. $i = 1;
22. for (; ; ) {
23. if ($i > 9) {
24. break;
25. }
26. echo $i;
27. $i++;
28. }
29. echo "</br>";
30.
31. /* example 4 */
32.
33. for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);
34. ?>
Output:
123456789
123456789
123456789
123456789
We can use for loop inside for loop in PHP, it is known as nested for loop. The inner for loop
executes only when the outer for loop condition is found true.
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. }
40
6. }
7. ?>
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
Output:
The foreach loop is used to traverse the array elements. It works only on array and object. It
will issue an error if you try to use it with the variables of different datatype.
41
The foreach loop works on elements basis rather than index. It provides an easiest way to
iterate the elements of an array.
Syntax
1. foreach ($array as $value) {
2. //code to be executed
3. }
Syntax
1. foreach ($array as $key => $element) {
2. //code to be executed
3. }
Flowchart
Example 1:
1. <?php
2. //declare array
3. $season = array ("Summer", "Winter", "Autumn", "Rainy");
4.
42
5. //access array elements using foreach loop
6. foreach ($season as $element) {
7. echo "$element";
8. echo "</br>";
9. }
10. ?>
Output:
Summer
Winter
Autumn
Rainy
Example 2:
1. <?php
2. //declare array
3. $employee = array (
4. "Name" => "Alex",
5. "Email" => "alex_jtp@gmail.com",
6. "Age" => 21,
7. "Gender" => "Male"
8. );
9.
10. //display associative array element through foreach loop
11. foreach ($employee as $key => $element) {
12. echo $key . " : " . $element;
13. echo "</br>";
14. }
15. ?>
Output:
Name : Alex
Email : alex_jtp@gmail.com
Age : 21
Gender : Male
Example 3:
Multi-dimensional array
1. <?php
2. //declare multi-dimensional array
3. $a = array();
4. $a[0][0] = "Alex";
43
5. $a[0][1] = "Bob";
6. $a[1][0] = "Camila";
7. $a[1][1] = "Denial";
8.
9. //display multi-dimensional array elements through foreach loop
10. foreach ($a as $e1) {
11. foreach ($e1 as $e2) {
12. echo "$e2\n";
13. }
14. }
15. ?>
Output:
Dynamic array
1. <?php
2. //dynamic array
3. foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) {
4. echo "$elements\n";
5. }
6. ?>
Output:
javatpoint
PHP While Loop
PHP while loop can be used to traverse set of code like for loop. The while loop executes a
block of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits
from the body of loop.
The while loop is also called an Entry control loop because the condition is checked before
entering the loop body. This means that first the condition is checked. If the condition is
true, the block of code will be executed.
Syntax
1. while(condition){
2. //code to be executed
3. }
Alternative Syntax
1. while(condition):
44
2. //code to be executed
3.
4. endwhile;
PHP While Loop Flowchart
Output:
1
2
3
4
5
6
7
8
9
10
45
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
Example
1. <?php
2. $i = 'A';
3. while ($i < 'H') {
4. echo $i;
5. $i++;
6. echo "</br>";
7. }
8. ?>
Output:
A
B
C
D
E
F
G
We can use while loop inside another while loop in PHP, it is known as nested while loop.
46
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
Syntax
1. while(true) {
2. //code to be executed
3. }
Example
1. <?php
2. while (true) {
3. echo "Hello Javatpoint!";
47
4. echo "</br>";
5. }
6. ?>
Output:
Hello Javatpoint!
Hello Javatpoint!
Hello Javatpoint!
Hello Javatpoint!
.
.
.
Hello Javatpoint!
Hello Javatpoint!
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.
The PHP do-while loop is used to execute a set of code of the program several times. If you
have to execute the loop at least once and the number of iterations is not even fixed, it is
recommended to use the do-while loop.
It executes the code at least one time always because the condition is checked after
executing the code.
The do-while loop is very much similar to the while loop except the condition check. The
main difference between both loops is that while loop checks the condition at the beginning,
whereas do-while loop checks the condition at the end of the loop.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
48
Flowchart
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
Example
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-
while loop, it is must that the program should not contain any other statements after the do-
while loop. In this case, it will not generate any error.
49
1. <?php
2. $x = 5;
3. do {
4. echo "Welcome to javatpoint! </br>";
5. $x++;
6. } while ($x < 10);
7. ?>
Output:
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Example
The following example will increment the value of $x at least once. Because the given
condition is false.
1. <?php
2. $x = 1;
3. do {
4. echo "1 is not greater than 10.";
5. echo "</br>";
6. $x++;
7. } while ($x > 10);
8. echo $x;
9. ?>
Output:
The while loop is also named as entry The do-while loop is also named as exit control
control loop. loop.
The body of the loop does not execute if The body of the loop executes at least once, even
the condition is false. if the condition is false.
50
Condition checks first, and then block of Block of statements executes first and then
statements executes. condition checks.
This loop does not use a semicolon to Do-while loop use semicolon to terminate the loop.
terminate the loop.
PHP Break
PHP break statement breaks the execution of the 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.
The break keyword immediately ends the execution of the loop or switch structure. It
breaks the current flow of the program at the specified condition and program control
resumes at the next statements outside the loop.
The break statement can be used in all types of loops such as while, do-while, for, foreach
loop, and also with switch case.
Syntax
1. jump statement;
2. break;
Flowchart
Let's see a simple example to break the execution of for loop if value of i is equal to 5.
51
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
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
The PHP break statement breaks the flow of switch case also.
52
1. <?php
2. $num=200;
3. switch($num){
4. case 100:
5. echo("number is equals to 100");
6. break;
7. case 200:
8. echo("number is equal to 200");
9. break;
10. case 50:
11. echo("number is equal to 300");
12. break;
13. default:
14. echo("number is not equal to 100, 200 or 500");
15. }
16. ?>
Output:
1. <?php
2. //declare an array of string
3. $number = array ("One", "Two", "Three", "Stop", "Four");
4. foreach ($number as $element) {
5. if ($element == "Stop") {
6. break;
7. }
8. echo "$element </br>";
9. }
10. ?>
Output:
One
Two
Three
You can see in the above output, after getting the specified condition true, break statement
immediately ends the loop and control is coming out from the loop.
53
It is not essential to break out of all cases of a switch statement. But if you want that only
one case to be executed, you have to use break statement.
1. <?php
2. $car = 'Mercedes Benz';
3. switch ($car) {
4. default:
5. echo '$car is not Mercedes Benz<br>';
6. case 'Orange':
7. echo '$car is Mercedes Benz';
8. }
9. ?>
Output:
The break accepts an optional numeric argument, which describes how many nested
structures it will exit. The default value is 1, which immediately exits from the enclosing
structure.
1. <?php
2. $i = 0;
3. while (++$i) {
4. switch ($i) {
5. case 5:
6. echo "At matched condition i = 5<br />\n";
7. break 1; // Exit only from the switch.
8. case 10:
9. echo "At matched condition i = 10; quitting<br />\n";
10. break 2; // Exit from the switch and the while.
11. default:
12. break;
13. }
14. }?>
Output:
At matched condition i = 5
At matched condition i = 10; quitting
54
Note: The break keyword immediately ends the execution of the current
structure.
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;
55
Flowchart:
Example
In the following example, we will print only those values of i and j that are same and skip
others.
1. <?php
2. //outer loop
3. for ($i =1; $i<=3; $i++) {
4. //inner loop
5. for ($j=1; $j<=3; $j++) {
6. if (!($i == $j) ) {
7. continue; //skip when i and j does not have same values
8. }
56
9. echo $i.$j;
10. echo "</br>";
11. }
12. }
13. ?>
Output:
11
22
33
Example
In the following example, we will print the even numbers between 1 to 20.
1. <?php
2. //php program to demonstrate the use of continue statement
3.
4. echo "Even numbers between 1 to 20: </br>";
5. $i = 1;
6. while ($i<=20) {
7. if ($i %2 == 1) {
8. $i++;
9. continue; //here it will skip rest of statements
10. }
11. echo $i;
12. echo "</br>";
13. $i++;
14. }
15. ?>
Output:
57
20
Example
The following example prints the value of array elements except those for which the
specified condition is true and continue statement is used.
1. <?php
2. $number = array ("One", "Two", "Three", "Stop", "Four");
3. foreach ($number as $element) {
4. if ($element == "Stop") {
5. continue;
6. }
7. echo "$element </br>";
8. }
9. ?>
Output:
One
Two
Three
Four
The continue statement accepts an optional numeric value, which is used accordingly. The
numeric value describes how many nested structures it will exit.
Example
PHP Function………………..
58