The Open Code Project

Common loops and switches in PHP and ASP/VBScript

June 16th,2009 by Allan Bogh

PHP

//PHP for loop
for($i=0; $i<count($array); $i++){
   echo $array[$i];
}

//PHP foreach
foreach($array as $key=>$val){
    echo $key; //this is the array position
    echo $val; //this is the value
    echo $array[$key]; //this is the same
}

//PHP breaking loops and inner loops
for($i = 0; $i < 10; $i++){
    for($j = 0; $j < 10; $j++){
         if($j == 7){
             break; //never gets here
         }else if($j == 6){
             break(2); //breaks at 6, 2 layers
         }
    }
}
            
$totalCount = count($array);
$i = 0;
//PHP while loop
while($i < $totalCount){
    echo $array[$i++];
}

$i = 0;
//PHP do while
do{
    echo $array[$i++];
} while($i < $totalCount);

//PHP if elseif
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

//PHP switch (this works for strings too)
switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
        echo "i is not equal to 0, 1 or 2";
}


ASP (classic) and VBScript

'ASP/VBScript Arrays
Dim myArray(9) 'this is 10 positions
myArray(0) = 0
'build the rest of the array...

'You could also do
Dim myArray()
ReDim myArray(0)
myArray(0) = 0
ReDim Preserve myArray(9) 'omit preserve to nullify all data
'build the rest of the array

'ASP for next
For i=0 to UBound(myArray)
    Response.Write myArray(i)
    'VBScript: WScript.Echo myArray(i)
Next

'ASP for each (foreach)
For Each val in myArray
    Response.Write val
Next

'ASP breaking loops and outer loops
MyLabel:
For i=0 to 9
    For j=0 to 9
        If j=7 Then
            Break
        Else If j=6 Then
            Break MyLabel
        End If
     Next
Next

Dim totalCount: totalCount = UBound(myArray)
i = 0
'ASP while loop
While i < totalCount
    Response.Write myArray(i)
    i = i + 1
Wend

i = 0
'ASP do while
Do While i < totalCount 'there's also a do until loop
    Response.Write myArray(i);
    i = i + 1
Loop

'ASP if elseif
If i = 0 Then
    Response.Write "i equals 0"
ElseIf i = 1 Then
    Response.Write "i equals 1"
ElseIf i = 2 Then
    Response.Write "i equals 2"
End If

'ASP Select Case (like switch, this works for strings too)
Select Case i
    Case 0
        Response.Write "i equals 0"
    Case 1
        Response.Write "i equals 1"
    Case 2
        Response.Write "i equals 2"
    Case Else
        Response.Write "i is not equal to 0, 1 or 2"
End Select

Comments (0)


:

:

:


: formatting help
Close

Formatting instructions:

You can use <a> tags but everything else will be stripped and your comment will look funny.

I swear, don't use html except the <a> tag or else some random star will supernova. Remember, we have a star right next to us, so don't try it.

This isn't bbcode either so don't use it. That is all.