phplearner
phplearner

Reputation: 1

PHP convert string to int seems to give me 0

     <?php $sizeh = '<script type="text/javascript">
                    document.write(viewportheight);</script>'; 

     echo $sizeh;
     echo  gettype ($num);

     $num = (int) $sizeh;
     //$num = intval($sizeh);
      echo  gettype ($num);
      echo $num;

 ?>

This results is:

1083  string  integer   0

Why I am getting the value of zero while that zero should be 1083 ??

Upvotes: 0

Views: 1074

Answers (4)

jeroen
jeroen

Reputation: 91734

The problem is that you are looking at the browser window and not at the source code: $sizeh is a string, starting with <script type .... When you cast that string to an integer, the result is 0.

You cannot capture the output of javascript in php as the php is processed first, then sent to the browser after which the browser executes the javascript. To send a javascript value back to php you would need to post a form or use ajax.

Upvotes: 0

RiaD
RiaD

Reputation: 47619

 <?php $sizeh = '<script type="text/javascript">
                document.write(viewportheight);</script>';

$sizeh now is this ugly string. You will see 1083 in your browser because your browser run JS. But it will after php stop works

Upvotes: 0

Marcelo
Marcelo

Reputation: 2302

You are mixing outputs from both JavaScript and PHP. 1083 is being written by JavaScript code. string, integer and 0 are being echoed by your PHP code.

Upvotes: 0

genesis
genesis

Reputation: 50966

you're trying to change int value from $sizeh, not from $num. $sizeh is that your javascript code

Look here

    <?php 
   $sizeh = '<script type="text/javascript">
                    document.write(viewportheight);</script>'; 
     $num = "1083";
     echo $sizeh;
     echo  gettype ($num)."  ";
     echo $num."  ";
     $num = (int) $num;
     //$num = intval($sizeh);
      echo  gettype ($num)." ";
      echo $num;

 ?>

Upvotes: 2

Related Questions