Link to home
Start Free TrialLog in
Avatar of jbpeake
jbpeake

asked on

PHP if statement won't work

This is an easy one, but for some reason it is stumping me.  The java script is working, and I can echo out the $width with no problems.  But, for some reason, when I try to use the $width in a PHP if statement I can't get it to work.  Even when i turn the screen resolution down to 800, and PHP echos out 800, it still prints "Print this on the screen.".  I've done things like this before, but for some reason I can't get this to work. I've got something wrong with my if statement, but I dont' know what.
<?
$width = "<script>document.write(screen.width);</script>";
echo $width;
if ( $width > "1023" ) {	
?>
	<strong> Print this on the screen.</strong>
<?
}
?>

Open in new window

Avatar of isaackhazi
isaackhazi

Yes you will have to add an else statement .......


<?
$width = "<script>document.write(screen.width);</script>";
echo $width;
if ( $width > "1023" ) {	
?>
	<strong> Print this on the screen.</strong>
<?
else
}
?>

Open in new window

What i mean is dont leave the else part balnak , put something in...

Cheers
You can't use the > sign when comparing a number to s string. So remove the quotes from the number as in the attached code.
<?
$width = "<script>document.write(screen.width);</script>";
echo $width;
if ( $width > 1023 ) {	
?>
	<strong> Print this on the screen.</strong>
<?
}
?>

Open in new window

Thats not the only problem.  You are trying to merge two different languages and it wont work like this.  Remember PHP is server side, and JS is client side.  What your PHP page is doing is outputting a javascript command.  Therefore as far as php is concerned $width is just a string.  PHP will never get the value of the screen like this.  The reason why you get the right number is because the javascript command is the one witting it to the screen not php.  The only way you could do this is to get the width in javascript and send it to a new page as a GET parameter like this newpage.php?width=1023.  Then you can have this php script in the new page and it will work because it will receive it as a parameter.
In other words the way you're doing it now only the client side (JavaScript) knows the value of the screen width.  You need to let the server (PHP) know the value and you do that through a get or post like I mentioned above.
Something like this would work:
Page1(Javascript):

<script>
var scrwidth=screen.width;
window.location = "secondpage.php?width="+scrwidth;
</script>

Then in page two (secondpage.php):
<?php
$width=$_GET['width'];
if ( $width > "1023" ) {        
?>
        <strong> Print this on the screen.</strong>
<?
}
?>

ASKER CERTIFIED SOLUTION
Avatar of digital0iced0
digital0iced0

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial