How to use for Loop in PHP

In this article, I will explain how the for Loop can be used in PHP.
  • 2169

for Loop in PHP

  • The for loop is used when you know in advance how many times the script should run or execute a statement.

  • The  for loop allows the user to put all the loop-related statements in one place.

  • The for loop structure is similar to C language.

Syntax

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

Parameters:

  • init: init used to initialize a counter value.
  • condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment: Mostly used to increment a counter value

Example

The following example show the for loop that Counting number of times a word present in a sentence.

<html>

<body>

<h2 style="color: firebrick;">for Loop example</h2>

    <?php 

    $sentance="The quick brown Fox jumps over the lazy Dog"; 

    $string = explode(" ", $sentance);

    $now = count($string); 

    $b = 0;

    for($a=0; $a<$now; $a++) 

    {    

    if ($string[$a] == "the" or $string[$a] == "The") 

    { 

    $b =  $b+1; 

    } 

    } 

    echo ("Total number of word is : "); 

    echo $b;

    ?>

</body>

</html>  

 

Output

for- loop.jpg

You may also want to read these related articles here
 
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 
© 2020 DotNetHeaven. All rights reserved.