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

Question:

Can you help me understand what's going on?

Why is it printing ZERO after conversion? Does it have to do with me populating 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 

?>

Answer:

Just replace the value of the $largura variable in the expression

$largura = (int)$largura;

to see what you want to convert to INT.

Making the substitution we have:

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

It is not possible to convert a javascript to INTEGER.

Actually, the string to integer conversion depends on the string format, so PHP evaluates the string format and if it doesn't have any numeric value it will be converted to 0(zero)

Regarding 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 a javascript on the page which in turn prints the value of the variable largura with document.write .

See how it works here . (doesn't allow javascript, so won't run document.write)

If you want to see javascript working, copy the code below and paste it on this page http://phptester.net/

$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';
Scroll to Top
AllEscort