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
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
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
Share on other sites

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.