php, if variable is over 300 echo 300

Associate
Joined
11 Oct 2008
Posts
268
I have a database table, and my site increases a number in the table by 30 everytime i click a button and then outputs it as a $variable.

does anyone know how i can use the if else code to make it echo a different variable if the number is anything over 300 ?
 
Ah, I gotta use > thanks :)

I have this:

PHP:
<?php

$max_number = "300";

if (pos_y > 300) {

echo $max_number;

else

echo $pos_y;

?>

and im getting errors, can you see what i did wrong?
 
missing a few { and } brackets.

I haven't touched PHP in awhile but I assume it needs to be something like:

if (blah) {
blah
} else {
blah
}

also missing $ from one of the variable names
 
Last edited:
Try This:

PHP:
<?php

$max_number = 300;

if ($pos_y > $max_number) {
  echo $max_number;
} else {
  echo $pos_y;
}
?>
 
This also does the same as the above code, it essentially says "echo the smallest number out of $pos_y and 300".

PHP:
<?php
  echo min($pos_y, 300);
?>
 
Ah, just thought of one more thing, sorry to keep bothering you guys, Is it possible to add to this code so aswell as 'if > 300 echo 300, it also checks if the number is below 0, and if so, it echos $minnumber which is 0

its because im using it for an image that is placed using absolute position, so if it goes past 300 its out of my content box, and if its less than 0 its also out of my box
 
This will bound your $pos_y variable between 0 and 300:

PHP:
<?php
  echo min(max($pos_y, 0), 300);
?>
 
Brackets are used to contain what happens..

Code:
if ($foo == $baz) {
  do this
  and this
  and this
} else {
  do this
  and this
  and this
}
You can omit using them if it's a singular thing happening
Code:
if ($foo == $bar) 
  do this

but I prefer to always use them for clarity.
 
Back
Top Bottom