5 Constant, Expression statements and PHP Control Statement

Hiren Joshi

epgp books

 

 

 

 

Constant

  • Constant stores a value which cannot be changed during program execution.
  • The syntax to define constant is: define(constantName, constantValue)
  • Though it is not rule, but to differentiate ConstantName from others, it is generally written in UPPERCASE letters.
  • For example: define(„PI‟,3.14)
  • Create a constant. The name of constant is PI and the value for the constant is 3.14.

Let us take an example to demonstrate the use of constant.

 

<html>

<body>

<form method=”post” action=”circlearea.php”>

Enter Radious:

<input type=”text” name=”radious”>

<br><br>

<input type=”submit” name=”submit” value=”Submit”>

<input type=”reset” name=”reset” value=”Reset”>

</form>

 

<?php

$r = $_POST[‘radious’];

define(‘PI’,3.14);

$area = PI * $r * $r;

echo “<br> Area of radious $r is $area sq meters”;

?>

</body>

</html>

 

In the above example, constant PI is defined with value 3.14. The value of PI is used to calculate area of circle.

 

From the above code, you can also observe that the HTML code can use in PHPfile. Here only a single file is used to do work of HTML – to get input from user – and PHP – process on input value; here it calculates area of a circle.

 

String Expression

 

An expression is a value. It can be a single value as default or it can be a resulted single value after a series of operations. It can be a combination of variable, values, operators or functions.

 

In PHP, string expression can be written using „‟ (single quotes) or “ “(double quotes).

For example:

$name = ‘Hiren’;

or

$name = “Hiren”;

 

You can use empty double quotes („‟“) or single quotes („‟) also to assign to a variable. Null is a special value which can be assigned to variable. Null is a special value. Null is different from empty string („‟”). Null is not case sensitive. So null or NULL behaves the same way.

 

$address = ‘’;

$address = NULL;

 

To insert a variable value into a string is known as interpolation. When double quotes (“ “) are used, PHP interpreter will check the entire string to see that is there any variables which need to be inserted into the string. While single quote („ ‟) will not insert variable value into string. Hence PHP works more efficiently when „ „ is used for string. Let‟s take one example:

 

<?php

$a = 10;

$b = “10”;

$c = $a + $b;

echo “value of c is $c”;

$d = ’10’;

$e = $a+ $d;

echo “<br>”;

echo ‘value of e is $e’;

?>

 

When you execute the program, the output will be

 

value of c is 20

value of e is $e

 

You can combine single and double quote for writing in quotes.

 

e.x.:

     <?php

$name = “O’Brien”;

echo $name;

echo “<br>”;

$line = ‘She said, “Hi!” ‘;

echo $line;

echo “<br>”;

$quotes = “quotation is: ‘will will find the way’ “;

echo $quotes;

echo “<br>”;

?>

 

The output of the above will be

 

O’Brien

She said, “Hi!”

quotation is: ‘will will find the way’

 

To join or concatenate two or more strings the concatenation operator (.) is used.

 

For example:

$fname = ‘Hiren’;

$lname = ‘Joshi’;

$fullname = $name.’ ‘.$laname   // Hiren Joshi

$price = 19;

$ans = ‘Price : ‘.$price; // Price : 19;

 

    Numeric Expression

 

Following operators are used for numeric expression:

Operator Description Example Result
+ Addition 7 + 3 10
Subtraction 7 – 3 4
* Multiplication 7 * 3 21
/ Division 7/3 2.33
% Modulus 7%3 1
++ Increment $count++ Adds 1 to count
Decrement $count– Subtracts 1 from count

When an expression having two or more operators, the order of precede is determines which operators are applied first.

Order of precedence can be override by using parentheses. The expression in parentheses is evaluated first.

 

For example:

7 + 3 * 5 will give you result 22 where as

(7+ 3) * 5 will give you result 50

 

Compound Assignment Operator:

 

To perform an operation on a variable and assign the result to the same variable, compound assignment statement is used. The compound operators are:

 

 

Introduction to Control Statement:

 

Control Statements allow you to control the execution of PHP statements. The control statements include branching statement, iterative statements.

 

To work with control statements, first we need to understand various operators. These operators are used in conditional expression. Conditional expression compares two expression and return TRUE or FALSE. If the condition is matched, it returns true otherwise false. For example, if we compare, $name == “Hiren”, it will return true, only if $name has value Hiren.

 

In the same way, it can work for $price == 10.

 

The == symbol is read as equal to. It compares the value is equal or not. The following table shows various relation operators.

 

Relational Operators

 

 

The && operator evaluate true only when all the condition are evaluate as true. The || operator evaluates true when any one conditions of the all condition is true. The ! operator will change the boolean value means true become false or false becomes true.

 

When two or more conditional expressions are joined using logical operator, it is known as compound expression.

 

In case a relational operator is used to compare two different data type, PHP automatically converts the data type to the same data type and attempts to perform the comparison. For example, if you write, $a=18, $b = „18‟, then $a == $b will be evaluated as true because PHP converts both the values to the same data type and then convert.

 

Not equal is compare not equality between two expressions.

 

All these relational operators are binary as it requires two operands (values) and one operator.

 

Branching Statement

 

If statement allows you control the execution of statements. If statement can only executes one or more php statement(s) only when the conditional expression is evaluated as true.

 

For example:

 

if ($age >= 18)

{

echo “You are eligible for voting”;

}

 

The general syntax of if statement is:

if (conditional expression)

{

statement(s);

}

[else if (conditional expression)

{

statement(s);

}

else if(conditional expression)

{

statement(s);

}

else

{

statement(s);

}]

 

The if statement can have one or more else if statement and else statement. The else if and else statements are optional. It can possible that after if statement immediately else statement is written. The else block will be executed as the condition for if block evaluated as false. A block means all the PHP statements inside the curly braces { }. It can possible that as per requirement there is only if block is coded.

 

Example 1:

 

$name = “Vimal”;

if($name != Null)

{

echo “Welcome $name”;

}

echo “<br> You are out of if blcok.” ;

 

Example 1 demonstrates the use of if block. There is only one if block. In PHP code, there can be more than one if block. In this example, $name is not null, hence the condition becomes true. So it will show, Welcome Vimal. Then if block completes, so after it, echo statement display You are out of if block.

 

Example 2:

 

if($amt == null)

{

echo “<br> You must enter amount”;

}

else if($amt <= 0)

{

echo “Amount must be greater than or equal to zero”;

}

 

In Example 2, the variable $amt is not set. So, the messages of undefined variable is display and the condition $amt == null is true, so in the browser it will display You must enter amount.

 

 The conditional expression evaluate as false, the statements after the if block will be executed. If block consist of opening and closing braces pair after the if statement.

 

Example 3:

 

$age = 18;

if ($age >= 18)

{

echo “<br> You are eligible for voting”;

echo “<br> You are eligible for driving license of a car”;

}

echo “<br> Your age is less than 18”;

 

The output of example 3 is

 

You are eligible for voting

You are eligible for driving license of a car

Your age is less than 18

 

Because though the condition for if statement is true, after if block there is not echo statement is executed.

 

The if –else if –else statement can be nested. That means in else –if or else block another if –else if – else statement written.

 

Switch Statement:

 

Switch statement can select one of many blocks of code to be executed. Switch statement be used instead of if-else if – else ladder.

 

Switch statement works with simple data type integer, string or float.

 

The general syntax for switch statement is:

 

Switch (switch expression)

{

case <case label 1>:

code to be executed for case label 1;

break;

case <case lable 2>:code to be executed for case label 1;

break;

….

[default:code to be executed for case label 1;break;

}

 

The switch expression in switch statement is returning a single value. This value is used to determine the case code to be executed. The switch expression can be a number or single variable or it may be a complex expression. The break statement is not compulsory though we have to use otherwise after the particular matching case is executed, it will also execute the next cases.

 

To understand the utility of switch, let us write the program first using if –else if – else and then using switch statement.

 

$grade = “B”;

if ($grade == ‘A’)

{

$message = ‘well above average’;

echo $message;

}

else if ($grade == ‘B’)

{

$message = ‘above average’;

echo $message;

}

else if ($grade == ‘C’)

{

$message = ‘average’;

echo $message;

}

else if ($grade == ‘D’)

{

$message = ‘below average’;

echo $message;

}

else if ($grade == ‘F’)

{

$message = ‘below average’;

echo $message;

}

else

{

$message = ‘invalid grade’;

 echo $message;

}

 

When the code is executed, it will display above average at the browser.Now write the program using switch statement .

    $grade = “B”;

switch($grade)

{

case ‘A’:

$message = ‘well above average’;

echo $message;

break;

case ‘B’:

$message = ‘above average’;

echo $message;

break;

case ‘C’:

$message = ‘average’;

echo $message;

break;

case ‘D’:

$message = ‘below average’;

echo $message;

break;

case ‘F’:$message = ‘failing’;

echo $message;

break;

default:

$message = ‘invalid grade’;

echo $message;

break;

}

 

When the code is executed, it will display above average at the browser.

 

If $grade = ‘Z’, then the program will display invalid grade.

 

If break statement is not written in none of the case, it will not break out of the switch block. Hence the code execute for all the cases after matching case.

 

For example,

$grade = “B”;

switch($grade)

{

case ‘A’:

$message = ‘well above average’;

echo “<br>”.$message;

 

case ‘B’:

$message = ‘above average’;

echo “<br>”.$message;

   case ‘C’:

$message = ‘average’;

echo “<br>”.$message;

 

case ‘D’:

$message = ‘below average’;

echo “<br>”.$message;

 

case ‘F’:

$message = ‘failing’;

echo “<br>”.$message;

 

default:

$message = ‘invalid grade’;

echo “<br>”.$message;

 

}

 

Then the output is:

above average

average

below average

failing

invalid grade

 

It is always a good practice to write break statement for each case

   

 Iterative Statements

 

Iterative statements are statements which are executed till the condition expression is satisfied.While and for are iterative statements. These are also known as while loop and for loop.

 

The general structure for while loop is:

 

Initialize a variable

While(condition)

{

Statement(s);

Initialized variable increment/decrement;

}

 

For example:

$i = 1;

While($i <= 10)

{

Echo “$i <br>”;

$i = $i + 1; // you can write as $i += 1 ;

}

 

The above code will print 1 to 10. Each number is printed in new line.

 

The while statement check the condition and execute while block till the condition evaluate as true. When the condition is false (in this case, $i = 11), the statement goes out of the while block.

 

If the condition is not false, the loop will be continue for infinite time. This type of loop is known as infinite loop.

 

For example, following code shows an infinite loop which print 1 continuously.

 

$i = 1;

While($i <= 10)

{

echo “$i <br>”;

}

 

The same program can be written by using for loop. For statement provides initializing, condition testing and increment, decrement in single line.

 

for($i=1;$i<=10;$i++)

{

echo “$i <br>”;

}

 

In a while or for loop, you can use break statement to break the loop. The continue statement is used to continue the execution.

 

$i = 1;

while($i <= 10)

{

echo “$i <br>”;

$i = $i + 1; // you can write as $i += 1 ;

if($i == 6)

{

break;

}

}

 

The above code snippet will print the value 1 2 3 4 5 . Each number is printed on new line. As the value of variable $i becomes 6, the code is break from while loop.

 

$i = 1;

while($i <= 10)

{

echo “$i <br>”;

$i = $i + 1; // you can write as $i += 1 ;

if($i == 6)

{

continue;

}

}

 

The above code snippet will print the value 1 2 3 4 5 6 7 8 9 10. Each number is printed on new line. As the value of variable $i becomes 6, the code is continue and is not terminated until the condition evaluates to false.

 

$i = 1;

while($i <= 10)

{

echo “$i <br>”;

$i = $i + 1; // you can write as $i += 1 ;

if($i == 6)

{

break;

}

}

 

The above code snippet will print the value 1 2 3 4 5. Each number is printed on new line. As the value of variable $i becomes 6, it is terminate from loop.

 

The same way you can use break and continue statement in for loop.

 

Do while loop is a loop which works same as while loop except that the statement execute at least once in do while even though the condition is false. For example,

 

$i = 10;

do

{

echo “$i <br>”;

$i = $i +1;

}while ($i <= 5)

The above code will print 10 as first it execute echo statement and then check the condition.

you can view video on Constant, Expression statements and PHP Control Statement

References:

  • Luke Welling, Laura Thomson: PHP and MySQL Web Development, Pearson,
  • W. Jason Gilmore: Beginning PHP and MySQL 5 From Novice to Professional,Apress
  • Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz, Michael K.
  • Glass: Beginning PHP5, Apache, and MySQL Web Development, Wrox,
  • Robin Nixon: Learning PHP, MySQL, and JavaScript, O’Reilly Media
  • Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove:Professional PHP, Wrox
  • Tim Converse, Joyce Park, Clark Morgan: PHP5 and MySQL Bible.
  • Joel Murach, Ray Harris: Murach’s PHP and MySQL, Shroff/Murach
  • Ivan Bayross, Web Enabled Commercial Application Development Using
  • HTML/Javascript/DHTML/PHP , BPB Publications
  • Julie C. Meloni, Sams Teach Yourself PHP, MySQL and Apache All in One, Sams
  • Larry Ullman, PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide,Pearson Education.
  • http://www.php.net.
  • http://www.w3schools.com/
  • http://www.tutorialspoint.com/