124697
124697

Reputation: 21893

what's wrong with this PHP function

I am trying to extract a value from an array if it exists in the array but i always get null even when I know the value does exist

this works

$data['key']

this doesn't work. getVal1 returns null

$sql2="INSERT INTO test (text, date) VALUES ('".getVal1('key',$data)."', NOW())";


function getVal1($name,$d){
        if ($d !=null && in_array($name, $d) ) {
            return $d[$name];
        }
        return null;
    }

Is there something wrong in my getVal1() function?

Upvotes: 0

Views: 72

Answers (2)

Steve
Steve

Reputation: 20469

Your problem is in_array searches for array values, yet you are passing it an array key.

You code can be simplified with isset and ternary if:

function getVal1($name,$d){
    return isset($d[$name])?$d[$name]:null;
}

Upvotes: 3

Zebra North
Zebra North

Reputation: 11492

You want:

if (isset($d[$name]))
    return $d[$name];
else
    return null;

Upvotes: 2

Related Questions