Chapter 1 - Expressions and Control Statements in PHP
Chapter 1 - Expressions and Control Statements in PHP
<?php
echo "Hello World!";
?>
● PHP Case Sensitivity
● In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are not case-sensitive.
Advantages of PHP
Following are the advantages of php which are as follows:
1. Open Source
2. Platform Independent
3. Simple and Easy -The one who knows any programming language can easily work on PHP. It is simple to learn, as its
learning curve is not large. The syntax is simple and flexible to use.
4. Database- PHP is easily connected with the database and make the connection securely with databases. It has a built-in
module that is used to connect to the database easily.
5. Fast- PHP applications can be easily loaded over the slow Internet and data speed.
6. Maintenance- PHP has great online support and community, which helps the new developers to help in writing the code
and developing the web applications.
7. Security -PHP frameworks built-in feature and tools make it easier to protect the web applications from the outer attacks and
security threats.
PHP Comments
● Single line comment : two slashes // or hash symbol #
● For Example :
<?php
// This is a single-line comment
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest(); // run function
echo $y; // output the new value for variable $y
?>
LOCAL SCOPE
A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:
Example
Variable with local scope:
Output :
<?php
function myTest() { Variable x inside function is: 5
$x = 5; // local scope
Variable x outside function is:
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
myTest();
myTest();
myTest();
?>
PHP Constants
● A constant is an identifier (name) for a simple value. The value cannot be changed
during the script.
● A valid constant name starts with a letter or underscore (no $ sign before the constant
name).
● Note: Unlike variables, constants are automatically global across the entire script.
Create a PHP Constant
To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)
Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false
Example : Create a constant with a case-sensitive name: Output :
<?php Welcome to W3Schools.com!
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Example : Create a constant with a case-insensitive name:
<?php
// case-insensitive constant name Output :
define("GREETING", "Welcome to W3Schools.com!", true); Welcome to W3Schools.com!
echo greeting;
PHP Constant Arrays
In PHP7, you can create an Array constant using the define() function.
Example
Create an Array constant:
<?php
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
?>
The echo statement can be used with or without parentheses: echo or echo().
Display Text
The following example shows how to output text with the echo command (notice that the
text can contain HTML markup):
Example Output:
<?php PHP is Fun!
echo "<h2>PHP is Fun!</h2>"; Hello world!
echo "Hello world!<br>"; I'm about to learn PHP!
echo "I'm about to learn PHP!<br>"; This string was made with multiple parameters.
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
The PHP print Statement
The print statement can be used with or without parentheses: print or print().
Display Text
The following example shows how to output text with the print command (notice that the
text can contain HTML markup):
Example
<?php Output:
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>"; PHP is Fun!
print "I'm about to learn PHP!"; Hello world!
?> I'm about to learn PHP!
PHP Data Types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
● String
● Integer
● Float (floating point numbers - also called double)
● Boolean
● Array
● Object
● NULL
● Resource
PHP String
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
● An integer must have at least one digit
● An integer must not have a decimal point
● An integer can be either positive or negative
● Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8),
or binary (base 2) notation
In the following example $x is an integer. The PHP var_dump() function returns the data
type and value:
Example
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Resource
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
PHP has two operators that are specially designed for strings.
Very often when you write code, you want to perform different actions for different
conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
● if statement - executes some code if one condition is true
● if...else statement - executes some code if a condition is true and another code if that
condition is false
● if...elseif...else statement - executes different codes for more than two conditions
● switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
Or
if (condition):
code to be executed if condition is true;
Endif;
Example
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
Nested If statement
● Syntax:
If(condition)
{
Block of statement;
If(condition)
{
Block of statement;
}
If(condition)
{
Block of statement;
}
}
Or
● Syntax:
If(condition):
Block of statement;
If(condition):
Block of statement;
endif;
If(condition):
Block of statement;
endif;
endif;
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example :Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
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 first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Example: 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!":
<?php
$t = date("H");
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
OR
Syntax
switch (n) :
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
endswitch;
Break Statement
● This statement is used to stop loop or switch statement at any time.
● For eg:
<?php
for ($x = 1; $x <= 5; $x++)
{
If($x==2)
Break;
echo "The number is: $x <br/>";
}
?>
Continue Statement
● This statement is used to skip an iteration of loop.
● For eg:
<?php
for ($x = 1; $x <= 5; $x++)
{
If($x==2)
continue;
echo "The number is: $x <br/>";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again a
certain number of times. So, instead of adding several almost equal code-lines in a script,
we can use loops.
Loops are used to execute the same block of code again and again, as long as a certain
condition is true.
In PHP, we have the following loop types:
● while - loops through a block of code as long as the specified condition is true
● do...while - loops through a block of code once, and then repeats the loop as long as
the specified condition is true
● for - loops through a block of code a specified number of times
● foreach - loops through a block of code for each element in an array
The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
Increment / Decrement operator;
}
Examples
The example below displays the numbers from 1 to 5:
Example
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
PHP do while Loop
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
Increment / Decrement operator;
} while (condition is true);
Example:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Note: In a do...while loop the condition is tested AFTER executing the statements within the loop. This means that the
do...while loop will execute its statements at least once, even if the condition is false. See example below.
The PHP for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
● init counter: Initialize the loop counter value
● test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
● increment counter: Increases the loop counter value
Examples
The example below displays the numbers from 0 to 10:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in
an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and
the array pointer is moved by one, until it reaches the last array element.
Examples
The following example will output the values of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
The $var_name is a normal variable used to store a value. It can store any value
like integer, float, char, string etc.
On the other hand, the $$var_name is known as reference variable where
$var_name is a normal variable. The $$var_name used to refer to the variable
with the name as value of the variable $var_name.
Example :
<?php
// Variable declaration and initialization
$var = "Hello";
$Hello = "GeeksforGeeks";
For example:
<?php Output :
function dot() HelloWorld
{ echo "Hello" . "World\n"; } HelloWorld
function comma()
{ echo "Hello" , "World\n"; }
dot();
comma();
?>