Jump to content

Defining variables


HuggieBear

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
Link to comment
https://forums.phpfreaks.com/topic/20844-defining-variables/
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]
Link to comment
https://forums.phpfreaks.com/topic/20844-defining-variables/#findComment-92284
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]
Link to comment
https://forums.phpfreaks.com/topic/20844-defining-variables/#findComment-92296
Share on other sites

Archived

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

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