简体   繁体   中英

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?

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;
}

You want:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM