# How to use ? and : in a program

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hi,

in the program below, what is the meaning/use of
the question mark (?gcd) and the colon (:\$a) after the return statement? Any
explanation will be appreciated.

<?
\$x=32;
\$y=80;
function gcd(\$a, \$b)
{ return (\$b>0)?gcd(\$b,\$a%\$b):\$a;}
\$val=gcd(\$x, \$y);
print "The greatest common denominator of \$x and \$y is \$val";
?>

This recursive program is used to find the greatest common denominator of 2
numbers.

TIA

## Re: How to use ? and : in a program

Michael Jack wrote:

Hi Michael,

It is just a shorthand notation for an if-then-else statement

eg:
\$a = 10;
echo ( (\$a<20) ? "\$a is smaller then 20!" : "\$a is not smaller then 20!");

is the same as:
\$a = 10;
if (\$a<20) {
echo "\$a is smaller then 20!";
} else {
echo "\$a is not smaller then 20!";
}

Regards,
Erwin Moller

## Re: How to use ? and : in a program

Many thanks for the prompt reply.

Regards,

"Erwin Moller"

Many thanks.

"Erwin Moller"

## Re: How to use ? and : in a program

Erwin Moller said the following on 11/10/2005 10:05:

Not quite. You couldn't use it for something like:

if (6 == \$a)
{
for (\$i = 0; \$i < \$a; ++i)
{
...
}
}
else
{
// Some other code
}

It's really a conditional assignment operator.

--
Oli

Oli Filth wrote:

True.
:-)

Regards,
Erwin Moller

## Re: How to use ? and : in a program

But it isn't an assignment operator.

--
http://yosemitecampsites.com/

## Re: How to use ? and : in a program

ellis@no.spam said the following on 11/10/2005 18:34:

Good point.

--
Oli

## Re: How to use ? and : in a program

Oli Filth wrote:

Slowly but surely we are getting there!
;-)

Regards,
Erwin Moller

## Re: How to use ? and : in a program

You have stumbled on the ternary operator;

But the real reason for this is to obfuscate the program and confuse