user1672299
user1672299

Reputation: 11

unable to set a variable's value inside an if block in PHP

Can someone explain why the $URL variable in this code is always set to 'Location: unknown.php' by the time the header($URL) is called?: If I comment out the declaration/initialization in the first line the code works, but I get a variable undeclared warning (I also get these warnings if I declare $URL before the if blocks without initializing it).

$URL = 'Location: unknown.php';
if ($spring){
    if (($leaves)&&(!$stem)&&(!$root)&&(!$head)&&(!$whole)){$URL = 'Location: snow-mold.php';}
} else if ($other) {
    if ((!$leaves)&&(!$stem)&&(!$root)&&($head)&&(!$whole)){$URL = 'Location: o01.php';}
    if (($whole) || ($root) ){$URL = 'Location: o02.php';}
    if (($leaves)&&($stem)&&(!$root)&&($head)&&(!$whole)){$URL = 'Location: o03.php';}
    if (($leaves)&&($stem)&&(!$root)&&(!$head)&&(!$whole)){$URL = 'Location: o04.php';}
    if ((!$leaves)&&($stem)&&(!$root)&&($head)&&(!$whole)){$URL = 'Location: o03.php';}
    if (($leaves)&&(!$stem)&&(!$root)&&($head)&&(!$whole)){$URL = 'Location: o05.php';}
    if ((!$leaves)&&($stem)&&(!$root)&&(!$head)&&(!$whole)){$URL = 'Location: o06.php';}
    if (($leaves)&&(!$stem)&&(!$root)&&(!$head)&&(!$whole)){$URL = 'Location: o07.php';}
}
header($URL);

Okay, I've simplified the code to highlight the problem...

$spring = (isset($_POST['season']) && strcmp($_POST['season'],'spring') == 0);
$URL = 'Location: unknown.php';
if ($spring){
    $URL = 'Location: snow-mold.php';
}
header($URL);

always redirects to unknown.php. If I change $URL = 'Location: unknown.php' to $URL;, the code redirects to snow-mold.php if and only if spring is selected, But I get a $URL undefined warning.

Upvotes: 1

Views: 125

Answers (1)

raina77ow
raina77ow

Reputation: 106443

Well, you can rewrite your code with series of if-elsif constructs - so your poor leaves won't be checked 7 times in that $other branch, for example.

But I'd suggest another approach: implementing a (sort of) hash function that takes all these tree parts as arguments (or, even better, a single associative array with these values as keys):

function happy_tree_hash($leaves, $stem, $root, $head, $whole) {
    // assuming each of this can be only TRUE or FALSE,
    // a bit mask should suffice:
    return (bool)$leaves << 4 
        | (bool)$stem << 3 
        | (bool)$root << 2 
        | (bool)$head << 1 
        | (bool)$whole;
}

... then assign value to your $url variable from a simple associative array:

$locations = array(
  5 => 'o02.php',  // whole and root
  16 => 'o07.php', // leaves only 
  ... 
);
...
$key = happy_tree_hash($leaves, $stem, $root, $head, $whole);
if (isset($locations[$key])) {
    $url = $locations[$key];
} else {
    $url = 'unknown.php'; 
}
header("Location: $url");

Upvotes: 2

Related Questions