-1

Can someone tell me why the output of echo of this Code is 13?

$a=10;
$b=2;
$j=$a/2;
for ($i=0;$i<$j;$i++){
    if ($i % $b == 1) 
    echo "$i";
}
Dharman
  • 30,962
  • 25
  • 85
  • 135

4 Answers4

3

Try this

<?php
    $a=10;
    $b=2;
    $j=$a/2;
    echo $j;
    echo "<br>";
    for ($i=0;$i<$j;$i++){
        if ($i % $b == 1) 
        echo "$i";
        echo "<br>";
    }
?>
  • because $a have 10 value , $b have 2 value and $j have 5 value

when start loop then $i start from 0 loop have max 5 loops from 0 to 4 so

  1. then loop start first then $i have 0 value so $i % will be equal 1 so nothing display
  2. when start second loop then $i have 1 value then $i % will be equal 1 so display 1 because now $i have 1 value
  3. when loop run third time then $i have 2 value then $i % will be equal 0 so nothing display
  4. when loop run fourth time then $i have 3 value then $i % will be equal 1 so display 3 because now $i have 3 value
  5. when loop run fifth time then $i have 4 value then $i % will be equal 0 so nothing display
Yasir Mehmood
  • 296
  • 2
  • 11
1
$a=10;
$b=2;
$j=$a/2;  //which will be 5
for ($i=0;$i<$j;$i++){ //the loop executes 5 times 
    if ($i % $b == 1) // this condition satisfies when $i becomes 1 && 3
    echo "$i"; //1 and 3 will be printed.
}

Check The comments written in your code

Vimal
  • 1,140
  • 1
  • 12
  • 26
0

You code is like this,

echo 1; echo 3;

output 13

LF00
  • 27,015
  • 29
  • 156
  • 295
0

I hope that will help you understand how your code works.

$a=10;
$b=2;
$j=$a/2;
for ($i=0;$i<$j;$i++){
    if ($i % $b == 1)
    echo "output"; 
    echo "$i";
}
Pardeep Kumar
  • 83
  • 1
  • 9