Page 1 of 1

Changing a Variable Depending on the IF stament (sorted now)

Posted: Wed May 31, 2006 6:36 am
by reecec
Hi


i need help on making the variable change depending on the if

eg.


if ($users==1) {people=2}

kind of thing

i was thinging like
if ($users==1) {then people=2}

i know that wont work but thats what i mean


thanks reece

Posted: Wed May 31, 2006 6:41 am
by twigletmac
You could use the ternary operator for a simple if ... else:

Code: Select all

$people = ($users == 1) ? 2 : 'some other value';
which is equivalent to:

Code: Select all

if ($users == 1) {
    $people = 2;
} else {
    $people = 'some other value';
}
Mac

thanks

Posted: Wed May 31, 2006 10:31 am
by reecec
Thanks for the code

i have tryed this and i get an error

Code: Select all

$chance = ($level == 1) ? 4
?>   THIS IS LINE 22 WHERE UNEXPECTED ; IS
Parse error: parse error, unexpected ';' in /home/reeceth/public_html/game/docrime.php on line 22


thanks alot reece

Posted: Wed May 31, 2006 10:34 am
by feyd
A ternary requires three (3) expressions. You've given two (2).

thanks

Posted: Wed May 31, 2006 10:38 am
by reecec
thanks thats done it so i could just have the same value again just so its 3


thanks reece

Posted: Wed May 31, 2006 10:39 am
by RobertGonzalez
Ternary syntax:

$var = ( if ) ? then : else;

hi

Posted: Wed May 31, 2006 11:02 am
by reecec
$chance = ($level == 1) ? 4 : 4;
$chance = ($level == 2) ? 4 : 4;
$chance = ($level == 3) ? 3 : 3;
$chance = ($level == 4) ? 3 : 3;
$chance = ($level == 5) ? 2 : 2;
$chance = ($level == 6) ? 2 : 2;

i think this is just taking the last value

please help

and thanks

Posted: Wed May 31, 2006 11:05 am
by ok
switch would be better:

Code: Select all

<?php
switch($level)
{
	case 1:
	case 2:
		$chance = 4;
	 break;
	case 3:
	case 4:
		 $chance = 3;
	break;
	case 5:
	case 6:
		$chance = 2;
	break;
}
?>

done

Posted: Wed May 31, 2006 11:10 am
by reecec
Thats perfect

thanks to all of you

Re: hi

Posted: Wed May 31, 2006 11:23 am
by RobertGonzalez
reecec wrote:

Code: Select all

<?php
$chance = ($level == 1) ? 4 : 4;
$chance = ($level == 2) ? 4 : 4;
$chance = ($level == 3) ? 3 : 3;
$chance = ($level == 4) ? 3 : 3;
$chance = ($level == 5) ? 2 : 2;
$chance = ($level == 6) ? 2 : 2;
?>
i think this is just taking the last value
In this code you are not setting a value based on an if, you are acutally setting a value to the same regardless. The switch statement is probably the better function to use (as was posted before me).

So you know, with the ternary operator, this...

Code: Select all

<?php
if ($x == 5)
{
    $var = 'not me';
}
else
{
    $var = 'me';
}
?>
becomes this...

Code: Select all

<?php
$var = ($x == 5) ? 'not me' : 'me';
?>