Jump to content

[SOLVED] If statement on one line. How?


Moon-Man.net

Recommended Posts

If you are referring to teh ternary operator it works like this...

 

$x = isset($y) ? 10 : 5;

 

so if y isset x will be 10 otherwise it will be 5. This method is only for assignment - you can't use for constructs or functions directly. You can however use the result for such operations.

$x = isset($y) ? 10 : 5;

That is what I saw. I don't quite understand how it works though, can someone help a little more please?

Thanks

-- Nathan

 

It's like he said...

 

<?php
$thisVar = isset($thatVar) ? 10 : 5;
?>

 

If $thatVar has been set prior to this point, $thisVar will be assigned a value of 10...otherwise, it will equal 5.

I believe it checks if $y has been set. The '?' checks true or false, then the first value before the ':' (which is ten in this case) will be what $x equals if it's true ($y has been set). Otherwise it will be false ($y has not been set) and $x will equal 5.

$x = isset($y) ? 10 : 5;

 

I hope that was clear.. and correct ;)

$x = $y >= 20 ? 10 : 5;

 

OK

 

$x = is the assignment part - this means that you will be assigning a value to $x

 

the next term before the ? is the conditional statement - in this if ($y > 20)....

 

? means condition is met (true) then use the next value (or calculation) ---- $x = 10;

 

: means condition is not met (false) then use this value (or calculation) ---- $x = 5;

 

so you could do.....

<?php
$x = $_GET['foo'] > $_GET['bar'] ? $_GET['foo'] / $_GET['bar'] : $_GET['bar'] / $_GET['foo'];
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.