How to compare a string to a number in and if else statement

Hi All

It has been ages since I have done any coding and I am struggling to find the answer to a very simple question.

I am using some javascript to get the height of the screen resolution of the device of the user:

$height = "<script>document.write(screen.height); </script>";

I am then using an if/else statement like this:

if ($height < 665) { echo ("don't show"); }

else { echo ("show"); }

For the life of me it is not working and I tested it all different ways and then realised that the $height variable is not a number and therefore was the comparison was not working.

How can I compare the two?


You can’t. AT first PHP runs on the server and after that JavaScript runs on the client. There is no way to get a direct interaction between the two.

1 Like

Ah… that makes sense… do you know if there is another way to get the screen height so it will work?

I worked it out… this is the code I used


 /* This code will be executed if screen resolution has not been detected.*/
 echo "<script language='JavaScript'>
 /* This code will be executed after screen resolution is detected.*/
    if(isset($_GET['Width']) && isset($_GET['Height'])) {
 // Resolution  detected
 //echo "<h1>Your screen resolution is ".$_GET['Width']." x ".$_GET['Height'].".</h1><br />";
 //Display page as per resolution
 if(($_GET['Height']>665)) {
 //echo "<b>This will be displayed when screen resolution is greater than 1024x768.</b>";
 else {
 //Display page as per resolution
 //echo "<b>This will be displayed when screen resolution is either equal to or less than 1024x768.</b>";
     else {
               // Resolution not detected

Wouldn’t it make more sense to do that in JS rather than PHP?

Or even better, using CSS with media queries?


.my-div {
    display: none;

@media only screen and (min-width: 665px) {
    .my-div {
        display: block;


<div class="my-div">I will be hidden when the screen is smaller than 665px</div>

What you are actually doing here is:-

if ("<script>document.write(screen.height); </script>" < 665) { }

or as PHP sees it:-

if ("Some random string of whatever" < 665) { }

Which will always be true.
To PHP that is just a string, it does not run javascript. The browser runs javascript, after PHP has finished doing its job on the server.

Exactly what I was going to suggest.
Except using a min-height query rather than width. :wink:


Ha, my mind is so used to using widths with media queries I didn’t even see it :laughing:

Thanks for pointing it out :slight_smile:


I’ve been using CSS for 10 years and the thought that min-height was even a thing didn’t occur to me until I saw this :exploding_head:


The height based queries have quite limited use cases, but they certainly exist.
I think I have used one, once ever…

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.