Jump to content

Archived

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

HuggieBear

Defining variables

Recommended Posts

In an attempt to write good code, I'm going to put [code=php:0]error_reporting(E_ALL);[/code] on all my pages.

I'd like to know how to define a variable.  I thought that you just had to assign something to it?

I'm getting the following error on my page:

[code]Notice: Undefined variable: bg in /home/domains/dizzie.co.uk/user/htdocs/php/pages.php on line 39[/code]

Now line 39 looks like this:

[code]$bg = ($bg == "#CCFF99" ? "#CCCC99" : "#CCFF99");[/code]

Now the first $bg is attempting to have something assigned to it, I'm assuming it's the 2nd $bg in that row that php has the problem with, but don't know how to get around this.  If I just add [code=php:0]$bg = "null";[/code] on the line before it, it's fine, but is there a better way to do this?

Regards
Huggie

Share this post


Link to post
Share on other sites
You've formatted your ternary operator incorrectly, it should be:
[code]<?php
$bg = ($bg == "#CCFF99") ? "#CCCC99" : "#CCFF99";
?>[/code]

Share this post


Link to post
Share on other sites
Thanks for that SA, I didn't notice that, but have corrected that now.

Any ideas on my define problem?

Huggie

Share this post


Link to post
Share on other sites
The ternary operator syntax is correct on both accounts, so it's just personal preference.. it could even be:[code]$bg = $bg == 'foo' ? 'val1' : 'val2';[/code]

the reason you are getting the define error is because you are attempting to use the variable before it has been defined - i.e. your comparison is the problem.

[code]<?php

$bg = isset($bg)
    ? $bg == '#CCFF99' ? $bg : '#CCCC99'
    : '#CCFF99'
;

?>[/code]

Share this post


Link to post
Share on other sites
Nested ternary operator's huh... I'll have to be careful here, but that worked thanks Jenk.

Can you possibly show me what this would look like if it was a nested 'if' statement, to help me better understand?

Huggie

Share this post


Link to post
Share on other sites
[code]<?php

if (isset($bg))
{
    if ($bg == '#CCFF99')
    {
        $bg = '#CCCC99';
    }
    else
    {
        $bg = '#CCFF99';
    }
}
else
{
    $bg = '#CCFF99';
}

?>[/code]

or shortened to:
[code]<?php

if (!isset($bg) || $bg == '#CCCC99') $bg = '#CCFF99';
else $bg = '#CCCC99';

?>[/code]

or in ternary:

[code]<?php

$bg = (!isset($bg) || $bg == '#CCCC99') ? '#CCFF99' : '#CCCC99';

?>[/code]

Share this post


Link to post
Share on other sites

×

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.