Forum Moderators: coopster

Message Too Old, No Replies

set variable if not set

         

optik

12:13 pm on May 24, 2010 (gmt 0)

10+ Year Member



Just wondering if there is a shorthand way of doing this like !$my_variable="value";

Rather than using if statements?

Matthew1980

12:27 pm on May 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Optik,

This would be the best I would say, a good old ternary:-

$my_variable = (isset(a_value) ? 'case true': 'case false');

Though it does depend on what you are trying to do, and the context of how you are doing it.

Cheers,
MRb

optik

8:44 pm on May 24, 2010 (gmt 0)

10+ Year Member



if (!isset($var)) {
$var="foo";
}

That's all I'm doing checking if the variable is set and if not setting the variable, just seems like that could be streamlined to a one liner.

Readie

8:53 pm on May 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It can be.

if (!isset($var)) {$var="foo";}
$var = (isset($var))? $var : 'foo';

Matthew1980

9:03 pm on May 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi all :)

Almost :)

Example:-

if (!isset($var)) {
$var="foo";
}


turns into this with a ternary:-

$var = (!isset($var) ? $var : 'foo');

It needs assigning if not set, though I am sure by now that you get the jist! ;-p I'm not arguing Readie! Honest! it's too humid for that!

Cheers,
MRb