0

I have a problem in my if else condition. My Screen Width is:1366 My code should show the if part but always it is showing the else part. I don't know WHY.. First of all i run the if condition without casting but problem was same... Then later on i casted into (int) but still the problem is same

$screenWidth = "<script>document.writeln(screen.width);</script>";
echo "Screen Width is:" . $screenWidth;
if( (int)$screenWidth > 500) 
{ 
    echo "if part:" . $screenWidth;
}
else 
{ 
    echo "else part:" . $screenWidth;
}
Affan
  • 71
  • 1
  • 6
  • 1
    PHP can't get that information from Javascript. In simplest terms, PHP runs before the page is loaded, and Javascript runs after the page is loaded. That's why. – larsAnders Apr 23 '16 at 04:48
  • But PHP is running this code: echo "Screen Width is:" . $screenWidth; and it is showing 1366. The problem is coming only in the ifelse condition – Affan Apr 23 '16 at 04:50
  • Yeh, right click your page and view the source, see how PHP is echo'ing the javascript... You will need to use javascript to load either one php file or an other for example. – Santy Apr 23 '16 at 04:51
  • 1
    Right, I can see how this is confusing. It's appearing because the variable $screenWidth is actually holding *a javascript string*. It's the same as writing `echo "Screen Width is:";` which gets rendered once the page loads, and you see a number instead of the javascript. But as far as PHP knows, $screenWidth itself is just a string, not a number. – larsAnders Apr 23 '16 at 04:56
  • 1
    remove (int) in if condition and also write 500 to '500' – Aslam Patel Apr 23 '16 at 04:59

1 Answers1

1

You really can't do this with PHP. Check out this question and answer. However, you can use Javascript to accomplish what you're after. It just requires a destination div to print the results.

<div id="output">
</div>

<script>
var screenWidth = screen.width;
if(screenWidth > 500){ 
    document.getElementById('output').innerHTML = "if part:" + screenWidth;
} else { 
    document.getElementById('output').innerHTML = "else part:" + screenWidth;
}
</script>
Community
  • 1
  • 1
larsAnders
  • 3,787
  • 1
  • 12
  • 19