0

I have a function named categories_name() which is given below:

function categories_name(){
    if($GLOBALS["pro_cat"] == "1"){
        $name_cat = "<a href='category.php cat_id=".$GLOBALS["pro_cat"]."'>Laptops</a>";
    }else if($GLOBALS["pro_cat"] == "2"){
        $name_cat = "<a href='category.php?cat_id=".$GLOBALS["pro_cat"]."'>Tablets</a>";
    }else if($GLOBALS["pro_cat"] == "3"){
        $name_cat = "<a href='category.php?cat_id=".$GLOBALS["pro_cat"]."'>Mobile Phones</a>";
    }else{
        echo "Not defined";
    }
    return $name_cat;
}

It basically returns the value of $name_cat.

But when I run this program I get this error:

Undefined variable: name_cat on line 2

Which supposed to be this:

return $name_cat;
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
  • 2
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) –  Feb 03 '18 at 07:57
  • shouldn't the last else be `$name_cat ="Not defined"` –  Feb 03 '18 at 07:58
  • If none of the `if` tests succeed, you never set `$name_cat`, so the variable is undefined. – Barmar Feb 03 '18 at 08:01
  • BTW, you should use `elseif` instead of nesting `if` statements. Or use `switch/case` since you're testing the same variable each time. – Barmar Feb 03 '18 at 08:02
  • Are you hitting `echo "Not defined";`? – Lawrence Cherone Feb 03 '18 at 08:03
  • See also [global versus $GLOBALS](https://stackoverflow.com/questions/3573847/php-global-or-globals) – Barmar Feb 03 '18 at 08:04

2 Answers2

1

you could also shorten your code. I see only the Label of the link gets changed.

Do this

function categories_name() {    
$link_title = '';
if ($GLOBALS["pro_cat"] == "1") {
    $link_title = 'Laptops';
} else if ($GLOBALS["pro_cat"] == "2") {
    $link_title = 'Tablets';
} else if ($GLOBALS["pro_cat"] == "3") {
    $link_title = 'Mobile Phones';
} else {
    $link_title = 'Undefined';
}
return "<a href='category.php?cat_id=" . $GLOBALS["pro_cat"] . "'>" . $link_title . "</a>";
}
Rotimi
  • 4,783
  • 4
  • 18
  • 27
0

This is not an error. This is s notice. Becouse you want to get non definded variable value php interpreter notice that the variabli is not definde. Try ad this to the beginning if you didn't want to get this notice:

error_reporting(E_ALL ^ E_NOTICE);
nagiyevel
  • 397
  • 3
  • 16