Jump to content

[SOLVED] "? :" What does it mean?


Recommended Posts

I've been teaching myself PHP and have seen people using the syntax, "? :".  I assume it is an alternative for a condition statement but I have been searching Google and can't find an explanation. 

 

Example:

$port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';

 

Please explain.

Link to comment
https://forums.phpfreaks.com/topic/123644-solved-what-does-it-mean/
Share on other sites

This syntax is not listed in the link provided but I know what it means now.  In the example that I gave it means:

 

If there is a port $port = $_SERVER["SERVER_PORT"];

 

If there isn't a port then $port = '';

 

Correct me if I'm wrong but, this is just a shortcut for IF/ELSE statement.

 

Thanks

 

Correct me if I'm wrong but, this is just a shortcut for IF/ELSE statement.

 

 

Not really but works in similar way.

 

You can't do

 

(mysql_connect($a,%b,$c,$d)) ? {$query = "query"; mysql_query($query); etc..} : {echo mysql_error();}

 

Ternary operator is best used, where you want to assign a value to a variable according to some condition.

For example

 

echo ($mysql_query("INSERT INTO ...")) ? "Data saved" : "Error: ".mysql_error();

You can't do

 

(mysql_connect($a,%b,$c,$d)) ? {$query = "query"; mysql_query($query); etc..} : {echo mysql_error();}

 

Because, per the documentation, those are not valid expressions. $query = "query" && mysql_query($query) might work, but then you're entering into a realm of sloppy code.

Hey sorry effigy, I only looked at the Comparison Operators table (obviously) and didn't think it was there.

 

Ternary operator is best used, where you want to assign a value to a variable according to some condition.

 

I see what you mean Mchl.  Just like in my example, you're assigning port to the SERVER_PORT if it exists but if not then assign nothing.

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.