Jump to content

[SOLVED] If statement on one line. How?


Moon-Man.net

Recommended Posts

I know how to do it one several lines, and I have seen it done on ONE line before useing a ":" I think.

this is how I know, what about any other ways?

 

if(statement){
Do something ;
}

 

How can I do this one one line?

if(isset($use_db)){
include('pg_connect.php') ;
}

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

$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.

Link to comment
Share on other sites

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 ;)

Link to comment
Share on other sites

$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'];
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.