Wednesday, June 27, 2018

Various loop statement in PHP

Loop statements are useful for getting data from arrays. We will see while, do while, for & foreach loops. Without wasting time just go with the below examples and give me your suggestion for improvements.


While statement: This loop will execute while the condition is true.
example: suppose you will pass digit 5 in the text box then you will get character 'e' as a result, try below HTML and PHP code.

HTML code (file name: input-number.html)
<html>
 <body> 
  <form method="post" action="show-result.php">
  <div style="position:relative; margin:25% auto; width:300px;">
 
   <input type="text" name="number" placeholder="Put number & get character" style="width:230px;"> &nbsp; <input type="submit" value="Submit">
 
  </div>
  </form>
 </body>
</html>

PHP code (file name: show-result.php)
<html>
 <body>
<?php

 error_reporting(E_ALL & ~E_NOTICE);
 $input = $_POST['number'];
 $chars = array(1=>'a', 2=>'b', 3=>'c', 4=>'d', 5=>'e');

 $result = '';

 while(list($key, $value) = each($chars)){
  if($input!=null && $input==$key)
   $result = '<div style="color:red; font-size:22px; font-weight:bold; width:150px; margin:25% auto; border:1px solid black; padding:20px; text-align:center;">' . $value . '</div>';
  if($input!=null && $input!=$key)
   $result = '<div style="color:red; font-size:22px; font-weight:bold; width:150px; margin:25% auto; border:1px solid black; padding:20px; text-align:center;"> Sorry no records!</div>';
 }

 echo $result;

?>
 </body>
</html>

For loop: When you know in advance how many times the loop will run.
Example: In the below code you will get result between 1 to 10.
<?php

for($i=1; $i<=10; $i++){
echo $i . "<br>";
}

?>

Do while: Loop will run at least one time even if the condition is false.
Example: Below code will give you result 11 and not execute number greater than 11.
<?php
$x=11;

do{
 echo $x . "<br>";
 $x++;
}while($x<=10);

?>

Foreach: It is used to get the result in key, value pair for better understanding take a look in the below example:

<?php

$cars = array('Toyota', 'BMW', 'Ferrari', 'Audi');

foreach($cars as $key=>$value){
 echo 'Car on position <b>' . $key . '</b> is: ' . $value . '<br>';
}

?>

Result:
Car on position 0 is: Toyota
Car on position 1 is: BMW
Car on position 2 is: Ferrari
Car on position 3 is: Audi

No comments:

Post a Comment