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;
}
5
  • 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. Commented Apr 23, 2016 at 4: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 Commented Apr 23, 2016 at 4: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. Commented Apr 23, 2016 at 4: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:<script>document.writeln(screen.width);</script>"; 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. Commented Apr 23, 2016 at 4:56
  • 1
    remove (int) in if condition and also write 500 to '500' Commented Apr 23, 2016 at 4:59

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.