-2

Here is the code:

 <?php 

      for($i =0, $x = 100 ; $i<1; $i++){

      echo $x .  'y' . $i+1 . ' = '. $i*$x . ' <br>';
      }

    ?>

My Expected Output was: 100 y 1 = 0

But the actual result was: 101 = 0;

Where did 'y' go?

https://ideone.com/n9HYGp

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Waqar
  • 826
  • 5
  • 16

3 Answers3

5

. have more operator precedence than +.

echo $x .  'y' . $i+1 = 101

Because it will operate as

echo ($x .  "y" . $i)+1 ;

This is what happens.

$x3=  ($x .  "y" . $i); //100y0
$u = $x3+1 ;  //101

You are doing + operation on a string. So the first digits before any characters will be taken as integer value.

Eg:

10y0g8 = 10
t10  =0

By doing an Arithmetic Operation, interpreter will convert string to integer, and it will discard all other characters. so 100y+1 = 101 it won't be 101y

Subin Thomas
  • 1,408
  • 10
  • 19
  • In your answer. $x3 = 100y0; then you add +1 in $x3 which becomes 101.. very confusing.. how 100y0 +1 = 101 ?? – Waqar Oct 17 '15 at 08:02
  • ok i can understand what you say. 100y0 +1 = 101... Fine ... why the answer is 101 and not 101y where did y go? – Waqar Oct 17 '15 at 08:14
  • ok beside this + operator, the compiler should have writter y after 101.. that what i say. – Waqar Oct 17 '15 at 08:17
  • 1
    is it what you said.. compiler will discard all other characters because it will convert string to integer.. .... CLEARED NOW THANKS MAN – Waqar Oct 17 '15 at 08:24
  • 2
    For the record, [it's not the compiler! it's the interpreter](http://stackoverflow.com/q/1514676/3709765) :) – someOne Oct 18 '15 at 03:45
  • thanks for the correction. I learned. :) One day i will be in a position to give better answers.. ONE DAY :) – Waqar Oct 18 '15 at 10:26
1

as explained in the above (Subin Thomas) answer the addition of 1 with the varchar value like 100y0 will add 1 with 100(the first occurence of integer). the following code will work as you expected

<?php 

  for($i =0 ,$x = 100; $i<1; $i++){

  echo $x .  'y' . ($i+1) . ' = '. $i*$x . ' <br>';
  }

?>
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59
0

To test :

<?php 

  for($i =0, $x = 100 ; $i<1; $i++){

  echo $x .  'y' . ($i+1) . ' = '. $i*$x . ' <br>';
  }

?>
scoolnico
  • 3,055
  • 14
  • 24
  • 1
    Obviously because of higher precedence of ().. But what if we donot put brackets.. just give explanation to the actual answer.. – Waqar Oct 17 '15 at 08:08
  • Have a look to http://php.net/manual/en/language.operators.string.php post #56... – scoolnico Oct 17 '15 at 08:14