Gregory Sims
Gregory Sims

Reputation: 561

array_key_exists always returning false

I have this code, written in php to return foo if bar is given and bar if foo is given. I have attempted, and seemingly failed to add a catch so that if anything other than foo or bar are input then "Unknown will be the output".

<?php
echo("<html><body bgcolor='#ffffff'><h1>Welcome</h1>");
$input = $_GET["foobar"];

$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

function getValue($value) {
    if(array_key_exists($value, $array)) {
        return $array[$value];
    } else {
        return "Unknown";
    }
}

echo ("Input: ". $input .", Output: ". getValue($input));

echo("<br><br>");

print_r($array);

echo("</body></html>"); ?>

However, it appears that the array_key_exists is always returning false as when I go to my page for either page.php?foobar=foo or page.php?foobar=bar I get this:

Welcome

Input: bar, Output: Unknown

Array ( [foo] => bar [bar] => foo )

or its opposite where the input is switched to foo but output remains "Unknown".

Upvotes: 0

Views: 833

Answers (2)

Sebas
Sebas

Reputation: 21542

My 50cts to complete Marc's answer, to propose an alternative to the global declaration:

<?php
echo("<html><body bgcolor='#ffffff'><h1>Welcome</h1>");
$input = $_GET["foobar"];

$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

function getValue($value) use (&$array) {
    if(array_key_exists($value, $array)) {
        return $array[$value];
    } else {
        return "Unknown";
    }
}

echo ("Input: ". $input .", Output: ". getValue($input));

echo("<br><br>");

print_r($array);

echo("</body></html>"); 
?>

Notice the use keyword in your function signature. This way you're passing a variable to the function's scope so it can see it.

Upvotes: 1

Marc B
Marc B

Reputation: 360872

Basic PHP: variables defined in a "parent" scope are NOT visible in "child" scopes:

$array = array(...); // global scope, top-level of the script

function getValue($value) {
    if(array_key_exists($value, $array)) {
                                ^^^^^^^---undefined local variable, function scope

You should have at least

global $array;

at the start of your getValue function.

Upvotes: 2

Related Questions