How to convert String to INT in the following situation :?

4

Can you help me understand what's going on?

Why after the conversion is it printing ZERO? Is there any way I can be popping the var with a javascript function to detect the resolution ???

<?php
$largura = "<script type =text/javascript> var largura =  screen.width; document.write(largura); </script>";

echo gettype($largura); //AQUI ELE IMPRIME string
echo $largura; //AQUI ELE IMPRIME 1366 

$largura = (int)$largura;

echo gettype($largura); //AQUI ELE IMPRIME integer
echo $largura; //AQUI ELE IMPRIME 0 

?>
    
asked by anonymous 14.12.2017 / 20:25

3 answers

1

Just replace the value of the $largura variable in the

$largura = (int)$largura;

to see what you want to convert to INT.

Replacing it we have:

$largura = (int)<script type =text/javascript> var largura = screen.width; document.write(largura); </script>;

You can not convert a javascript to INTEGER.

  

In fact, the conversion from string to integer depends on the format of the string, so PHP evaluates the format of the string and if it does not have any numerical value it will be converted to 0

For echo $largura; , replacing the value of the variable $largura we have:

echo "<script type =text/javascript> var largura =  screen.width; document.write(largura); </script>"

which prints on the page a javascript that in turn prints the value of the variable largura with document.write .

  

See how here . (does not allow javascript, so it will not execute the document.write)

If you would like to see javascript working, please copy and paste the following code: link

$largura = "<script type =text/javascript> var largura =  screen.width; document.write(largura); </script>";
echo "<br>";
echo gettype($largura). " AQUI ELE IMPRIME string";
echo "<br><br>";
echo "proxima linha é o javaScript veja no código fonte do frame direito";
echo "<br><br>";
echo $largura. " AQUI o JAVASCRIPT IMPRIME a largura";
echo "<br><br>querendo passar para INT um código javascript<br><br>";
$largura = (int)$largura;
echo $largura; 
echo "<br><br>";
echo gettype($largura). ' AQUI ELE IMPRIME integer porque agora $largura = 0';
echo "<br><br>";
echo $largura. ' AQUI ELE IMPRIME 0 porque $largura é 0';
    
15.12.2017 / 04:57
0

I think that from the moment you pass the string variable as a type (int), the variable does not recognize the characters within the string as a numeric value and places the value 0. I hope I have helped

    
14.12.2017 / 20:34
0

This happens because when you do (int)$largura , PHP does not interpret the javascript code, it simply takes all the content and tries to transform it into a numeral. Since there is no number to return, it returns 0.

The first result only appears the number, because PHP is printing this code on the page and the browser is interpreting the JS code. So the first form works and the second does not.

Maybe this link will help you. link

    
14.12.2017 / 20:34