Friday, 20 October 2017

Control Structures like For,Foreach,Switch


Control Structures like For,Foreach,witch
for
The for loop is the same as javascript's:
for($i=1;$i<=2;$i++)
{
print "This is $i<br>";
}
//This is 1
//This is 2

foreach
This is used to access the items in an array. For instance:

$arr=array("cat","dog","aadvark");
foreach($arr as $value){
echo"Value: $value<br>\n";
//Value: cat
//Value: dog
//Value: aadvark

switch
The switch statement is also the same as the one in JavaScript. A switch statement will continue to, in the example below, print all the statements after finding one that is true, so breaks are used to prevent this. Each statement is followed by a break, usually.

$i=1;
switch($i)
{
 //the variable is in brackets and the cases are in curly brackets
case 0:
print "zero";
break;
case 1:
print "one";
break;
default: //You can do a default case where the variable is something else!
print "whatever it is, it isn't 0, 1 or 2";
}
//result: one

The switch statement can deal with any simple type of data such as integers, floats and strings. This next example is the same as before in structure, except it uses strings:

$i="tomatoes";
switch ($i)
{
case "potatoes":
print "spuds";
break;
case "tomatoes":
print "toms";
break;
default:
print "Well, it could be anything!";
}

0 comments

Post a Comment