Control statements in PHP are used to control the flow of execution in a script. There are three categories of control statements in PHP: selection statements, iteration / loop statements and jump statements.
Selection statements
The selection statements in PHP allows the PHP processor to select a set of statements based on the truth value of a condition or Boolean expression. Selection statements in PHP are if, if-else, elseif ladder and switch statement.
Syntax of if is given below:
if(condition / expression)
{
statements(s);
}
Syntax of if-else is given below:
if(condition / expression)
{
statements(s);
}
else
{
statements(s);
}
Syntax of elseif ladder is given below:
if(condition / expression)
{
statements(s);
}
elseif(condition / expression)
{
statements(s);
}
elseif(condition / expression)
{
statements(s);
}
else
{
statements(s);
}
Syntax of switch statement is shown below:
switch(expression)
{
case label1:
statement(s);
break;
case label2:
statement(s);
break;
case label3:
statement(s);
break;
default:
statement(s);
}
The labels for case statements can be either an integer, double or a string. The default block is optional. If the break statement is absent, the following cases will also execute until a break statement is found.
Iteration or Loop Statements
The iteration statements in PHP allows PHP processor to iterate over or repeat a set of statements for a finite or infinite times. Iteration statements supported by PHP are while, do-while, for and foreach.
Syntax of while loop is given below:
while(condition / expression)
{
statements(s);
}
Syntax of do-while loop is given below:
do
{
statement(s);
}
while(condition / expression);
Syntax of for loop is given below:
for(initialization; condition / expression; increment/decrement)
{
statement(s);
}
The foreach loop is used to iterate over array elements and its syntax is given below:
//For normal arrays
foreach(array as variable_name)
{
statement(s);
}
or
//For associative arrays
foreach(array as key => value)
{
statement(s);
}
Jump Statements
The jump statements available in PHP are break and continue. The break statement is used to break the control from a loop, take it to the next statement after the loop and continue is used to skip the control from current line to the next iteration of the loop.
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply