What is Control Structures ?

The word control tells set of parameter of condition by way program control “flows” and Word Structure tell process after parameter is match with conditions.

Definition

Control Structures in a program are the branching/decision making constructs like the if, if-else, nested if-else, loops( for, while & do loops, foreach ) statement.

If else

The if statement allows to execute a code fragment/process, when the condition is met.in other way when the condition is not met the else part will.

Code

if ($a > $b) {
  echo "a is greater than b";
} else{
  echo "a is NOT greater than b";
}

The ternary operator as shorthand syntax for if-else
The ternary operator evaluates something based on a condition being true or not. It allows to quickly test a condition and often replaces a multi-line if statement.
Code

$b=2;
echo ($a > $b) ? "a is greater than b" : "a is NOT greater than b";
//Outputs: a is NOT greater than b.

Loops

For Loop

For loops are typically used when you have a piece of code which you want to repeat a given number of times.

Code

for ($i = 1; $i < 10; $i++) {
   echo $i;
}
//Outputs: 123456789

While

While loop iterates through a block of code as long as a specified condition is true.

Code

$i = 1;
while ($i < 10) {
   echo $i;
   $i++;
}
//Output: 123456789

Do-while

Do while loop first executes a block of code once, in every case, then iterates through that block of code as long as a specified condition is true.
Code

$i = 0;
do {
   $i++;
   echo $i;
} while ($i < 10);
//Output: `12345678910`

Foreach

Foreach is a construct, which enables you to iterate over arrays and objects easily.

Code

$array = [1, 2, 3];
foreach ($array as $value) {
   echo $value;
}
//Outputs: 123.

Switch

The switch structure performs the same function as a series of if statements, but can do the job in fewer lines of code.The value to be tested, as defined in the switch statement, is compared for equality with the values in each of the case statements until a match is found and the code in that block is executed.

Code

$colour = "red";
switch ($colour) {
   case "red":
      echo "The colour is Red";
      break;
   case "green":
   case "blue":
      echo "The colour is Green or Blue";
      break;
   case "yellow":
      echo "The colour is Yellow";
      break;
   case "black":
      echo The colour is Black";
      break;
   default:
      echo "The colour is something else";
      break;
}

In Switch is used for testing and any expression to the case statement.

Code

$i = 1048;
switch (true) {
   case ($i > 0):
      echo "more than 0";
      break;
   case ($i > 100):
      echo "more than 100";
      break;
   case ($i > 1000):
      echo "more than 1000";
      break;
}
(Visited 469 times, 1 visits today)
Share with Friends :

Leave a Reply

Your email address will not be published. Required fields are marked *