spacer
spacer
spacer

Looping Statements

Tonight we demonstrate the two most basic loop types using a digitized gallery of paintings from Mary Ellis.

We can show all her paintings as thumbnails using a while loop:


	<table border=0 cellpadding=5 cellspacing=0 width=100%>
            <tr>
         	<?php
			$i=1;
			$base_url = "http://bdcampbell.net/dynphp/gallery/full/";
			while ($i<=21) {
				echo '		<td width=100% valign=top><a href='.$base_url.'full'.$i.'.png"><img src="'.$base_url.'full'.$i++.'.png" width="64"></a></td>';
				echo "\n";
			}
		?>
            </tr>
	</table>

We played around with using an in-line style sheet to position the content dynamically:

		<?php
				$i=1;
				$base_url = "http://bdcampbell.net/dynphp/gallery/full/";
				while ($i<=21) {
					if(true) {
						echo '<div style="position:absolute;left:'.(rand(10, 280)).'px;top:'.(rand(10, 280)).'px"><a href="'.$base_url.'full'.$i.'.png"><img src="'.$base_url.'full'.$i.'.png" width="64" alt="mary pic" /></a></div>';
						echo "\n";
					}
					$i = $i + 1;
				}
		?>
Remember that the while statement executes a block of code if and as long as a specified condition evaluates to true. If the condition becomes
false, the statements within the loop stop executing and control passes to the statement following the loop.

The For Loop

Let's look at another presentation of the gallery thumbnails using a for Loop:


	<table border=0 cellpadding=5 cellspacing=0 width="800">
			<?php
				$i=1;
				$base_url = "http://bdcampbell.net/dynphp/gallery/full/";
            	echo '<font COLOR="red" face=Verdana>Mary Ellis</font>';
				for ($j=0; $j<6; $j++) {
					echo '	<tr>';
					echo "\n";
					echo '		<td width=100% valign=top><a href="'.$base_url.'full'.$i.'.png"><img src="'.$base_url.'full'.$i++.'.png"></a></td>';
					echo "\n";
					echo '		<td width=100% valign=top><a href="'.$base_url.'full'.$i.'.png"><img src="'.$base_url.'full'.$i++.'.png"></a></td>';
					echo "\n";
					echo '		<td width=100% valign=top><a href="'.$base_url.'full'.$i.'.png"><img src="'.$base_url.'full'.$i++.'.png"></a></td>';
					echo "\n";
					echo '	</tr>';					
					echo "\n";
				}
			?>
	</table>

The For statement loop is used when you know how many times you want to execute a statement or a list of statements. For this reason,
the For loop is known as a definite loop. The syntax of For loops is a bit more complex, though for loops are often more convenient than While loops. The For loop syntax is as follows: 

for (initialization; condition; increment)
{
   code to be executed;
}

The For statement takes three expressions inside its parentheses, separated by semi-colons. When the For loop executes, the following occurs:

  • The initializing expression is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
  • The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the For loop terminates.
  • The update expression increment executes.
  • The statements execute, and control returns to step 2.

Review the example that prints out prime numbers between 2 and 1000:

<html>
<head>
<title>Determination of Primes</title>
</head>
<body>
<?php
$i=0;
for($n=0;$n<1000;$n++) {
$prime = true;
for($t=2;$t<$n-1;$t++) {
if($n % $t == 0) {
$prime = false;
}
}
if($prime==true) {
echo $n." is prime";
echo "<br />";
$i++;
}
}
echo "we found ".$i." prime numbers";
echo "<br />";
?>
</body>
</html>


Break and Continue Statements

Sometimes you may want to let the loops start without any condition, and allow the statements inside the brackets to decide when to exit the loop. There are two special statements that can be used inside loops: Break and Continue.

The Break statement terminates the current While or For loop and continues executing the code that follows after the loop (if any). Optionally, you can put a number after the Break keyword indicating how many levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of the outermost loop.

Examples below show how to use the break statement:

<?php
echo "<p><b>Example of using the Break statement:</b></p>";

for ($i=0; $i<=10; $i++) {
   if ($i==3){break;} 
   echo "The number is ".$i;
   echo "<br />";
}

echo "<p><b>One more example of using the Break statement:</b><p>";

$i = 0;
$j = 0;

while ($i < 10) {
  while ($j < 10) {
    if ($j == 5) {break 2;} // breaks out of two while loops
      echo "The first number is ".$i."<br />";
      echo "The second number is ".$j."<br />";
    $j++;
  }
  $i++;
}

?>

The Continue statement terminates execution of the block of statements in a While or For loop and continues execution of the loop with the next iteration:

<?php
echo "<p><b>Example of using the Continue statement:</b><p>";

for ($i=0; $i<=10; $i++) {
   if ($i==3){continue;} 
   echo "The number is ".$i; 
   echo "<br />";
}
?>

Back to top

String Manipulations

In this section, we will learn different ways of manipulating string through PHP coding. Some of these are basic coding techniques while some will require using built-in functions of PHP for advance string manipulation.

String Concatenation

One of the most simplest string manipulation activity that can be done is concatenating two or more strings to form a single string. For example: $a might hold a string called "First" and $b might hold a string called "Second". To concatenate these two strings into one, we use a '.' (dot). See this example:

<?php
$a 
"First";
$b "Second";
$c "Third";

echo 
$a $b//using a . (dot) in between $a and $b

echo $a $b $c//three strings together

$d $a $b//concatenating $a, $b and storing in $d

echo $d//printing $d

echo "\$a is holding a string called"." ".$a;  
?>

Change the case of a string to lowercase and UPPERCASE

That's quite easy! All we need to do is use the built-in function called strtolower() to convert a string to lowercase and strtoupper() for uppercase conversions. See the example to convert a string to lowercase and uppercase.

<?php
$string 
"PHP is a GREAT Programming Language!";
$new_string strtolower($string);

echo 
$new_string;
//Output: php is a great programming language!

$new_string strtoupper($string);

echo 
$new_string;
//Output: PHP IS A GREAT PROGRAMMING LANGUAGE!
?>

Now, use the above example but replace the used functions with ucwords() (Uppercase the first character of each word in the string) and also ucfirst().

Determining position of first occurrence of a string

This is easy one! We will use yet another handy built-in function called strpos(). The syntax of strpos() is:

strpos ( string, keyword [, int offset] )

This will return 'FALSE' if the keyword is not found in the string and you will have to use '===' (strict comparison) to check the returned value. See the below example for usage of strpos().

<?php
$string 
"PHP is a GREAT Programming Language!";
$keyword "GREAT";

#Searching for keyword in the string
$position strpos($string$keyword);

echo 
$position//Output: 9 (9th position of Keyword)
?>

<?php
#conditional usage of strpos()
$string "This is a simple string";
$keyword "simple";
$keyword_1 "MySQL";

if (
strpos($string$keyword) > ) {
    echo 
"String found";
    } else {
    echo 
"String not found";
    }
?>

<?php
#conditional usage of strpos()
$string "This is a simple string";
$keyword "MySQL";

if (
strpos($string$keyword) > ) {
    echo 
"String found";
    } else {
    echo 
"String not found";
    }
?>

Return portion of a string from a given string

To get portion of a string from a given string we will make use of substr() function of PHP. The syntax is:

substr ( string , int start [, int length] )

Remember, the position of the first character of the string is always '0'. The function will take the start position and return a portion of the string from the start position as specified. You may optionally also mention the end position till which you want to get the portion of any given string. For example, in the string "Hello", the letter 'H' is at position '0' and the letter 'o' is at position '4'. See this example:

<?php
$string 
"PHP is GREAT Programming Language!";

#Returning portion of the above string from 0 to 12
$str substr($string,0,12);

echo 
$str//Output: PHP is GREAT (includes two spaces as well)

#Let's also concatenate something to $str

echo $str." Programming Language!";
?>

Adding slashes to string

Under various circumstances, you will need to automatically add slashes to escape special characters in a string. Be it storing in database table, or for anything else. Here's how we can do it with built-in addslashes() function. The syntax is:

addslashes ( string )

Below is an example to add slashes to any given string.

<?php
$string 
"Let's learn PHP. It's fun!";
$new_string addslashes($string);
echo 
$new_string//output: Let\'s learn PHP. It\'s fun!

#You can also do this directly without storing it in $new_string
echo addslashes($string); //works too! 
?>

OPOD Moderator's Code

  <?php include("../header_test.php") ?>
<?php include("../menu_test.php") ?>
		<div id="content_main">
			<div id="sectionhead">
                OCEAN PICTURE OF THE DAY (OPOD)
			</div>
<?php include("../action/menu.php") ?>
		    <div id="right_col">
              <div id="content">
			  <table bgcolor="white" border="0" cellpadding="10" cellspacing="0" width="780">
              <tr>
              <td>
              <table width="780" bgcolor="white">
                <tr>
                <td align="center" valign="middle">
                    <center><h1>OPOD Monitoring<br />
                    <?php print(Date("l, F d, Y")); ?></h1></center>
                </td>
            </tr>
          </table>
	  	  <?php
			//Connect To Database
			$hostname='mysql27.secureserver.net';
			$username='oceanweb';
			$password='password';
			$dbname='oceanweb';

            $con = mysql_connect($hostname,$username,$password); 
    
            //Connect
            if (!$con) 
            { 
                die('Could not connect: ' . mysql_error()); 
            } 
            mysql_select_db($dbname, $con);
            
            $status=$_REQUEST['status']; 
            $submitdate=$_REQUEST['dsubmitDate'];
            
            $id="";
            
            $result = mysql_query("SELECT submits.id FROM user, pic, submits WHERE user.id = submits.user_id AND pic.id = submits.picture_id AND submits.status = 0 ORDER BY date LIMIT 1");
        
            if($result) {
                if($row = mysql_fetch_array($result)) {
                    $id = $row['id'];
                    $sql2 = mysql_query("UPDATE submits SET status='".$status."', picture_id='".$id."', user_id='".$id."', use_date='".$submitdate."' WHERE id=".$id);
					echo '     <span class="instruction" style="font-size: 14px; font-weight:bold; color: #000000">Update Processed: Submission ID: '.$id.'   DATE: '.$submitdate.'   STATUS: '.$status.'</span>';
                }
            } else {
                //echo 'No results from query';
            }	 
            
            echo '<table width="80%" border="0" bordercolor="#ffffff" bgcolor="#ffffff" id="Report" align="center">';
            echo '<tr>';
            echo '<td></td>';
            echo '</tr></table><p> </p>';
            mysql_close($con); 
        ?>  
        
        <table width="80%" border="0" bordercolor="#ffffff" bgcolor="#ffffff" id="Report" align="center">
            <tr>
               <td bgcolor="#FFFFFF"><span class="instruction" style="font-size: 14px; font-weight:bold; color: #000000">Monitor Progress Report:</span></td>
            </tr>
            <tr>
               <td bgcolor="#CCCCCC"><div align="left"><span style="color: #000000">
                    <?php
                        // LINKUP ////
                        //Connect To Database
                        $hostname='mysql27.secureserver.net';
                        $username='oceanweb';
                        $password='password';
                        $dbname='oceanweb';
                        $incoming=$_REQUEST['incoming'];
                        
                        //connect to database
                        mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database!.');
                        //select - use this database 
                        mysql_select_db($dbname);
                        
                        //$query13 = "SELECT COUNT(*) as Num_unreview FROM 'submits' WHERE status = '0'";
                        
                        $result = mysql_query("SELECT * FROM submits");
                        $num_rows = mysql_num_rows($result);
                        
                        echo'<span class="instruction" style="font-size: 12px";>Total Opod Records:</span>';
                        echo "$num_rows";
                        echo  '<br />';						
                        echo  '</span>';	
                        echo  '</div>';	
                        echo  '</td>';	
                        echo  '</tr>';	
                        echo  '<tr>';	
                        echo  '<td>';		
                                                    
                        $result = mysql_query("SELECT * FROM submits WHERE status = 1 OR status = 2");
                        $num_rows = mysql_num_rows($result);
                        
                        echo'<span class="instruction" style="font-size: 12px";>Records Processed:</span>';
                        echo'<span class="Awaiting">'."$num_rows".'</span>';
                        echo  '<br />';                        
                        echo  '</td>';	
                        echo  '</tr>';	
                        echo  '<tr>';	
                        echo  '<td>';	
                                                         
                        $result = mysql_query("SELECT * FROM submits WHERE status = 0");
                        $num_rows = mysql_num_rows($result);
                        
                        echo'<span class="instruction" style="font-size: 12px";>Records Not Processed:</span>';
                        echo'<span class="Awaiting">'."$num_rows".'</span>';
                        echo  '<br />';         
                        echo  '</td>';	
                        echo  '</tr>';	
                        echo  '<tr>';	
                        echo  '<td>';				
    
                        $result = mysql_query("SELECT * FROM submits WHERE status = 1");
                        $num_rows = mysql_num_rows($result);
                        
                        echo'<span class="instruction" style="font-size: 12px";>Records Approved:</span>';
                        echo '<span class="Success">'."$num_rows".'</span>';
                        echo  '<br />';
                        echo  '</td>';	
                        echo  '</tr>';	
                        echo  '<tr>';	
                        echo  '<td>';	
    
                        $result = mysql_query("SELECT * FROM submits WHERE status = 2");
                        $num_rows = mysql_num_rows($result);
                        
                        echo'<span class="instruction" style="font-size: 12px";>Records Declined:</span>';
                        echo '<span class="Exists">'."$num_rows".'</span>';
                        echo  '<br />';
                        echo  '</td>';	
                        echo  '</tr>';	
                        echo  '</table>';	
                    ?>
                    <p> </p>
                    <p>               <a href="http://theoceanproject.org/opod/MonitorLogin.php">Process Next Submission</a></p>
          </td></tr></table>
          </div></div>
        <div id="footer" style="left:464px;top:712px">
        <table>
            <tr>
                <td style="background:transparent">
<?php include("../footer_div.php") ?>
</div>
</body>
</html>