简体   繁体   English

这个PHP函数怎么了

[英]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 我正在尝试从数组中提取一个值(如果它存在于数组中),但是即使我知道该值确实存在,我也总是会得到null

this works 这有效

$data['key']

this doesn't work. 这行不通。 getVal1 returns null getVal1返回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? 我的getVal1()函数有问题吗?

Your problem is in_array searches for array values, yet you are passing it an array key. 您的问题是in_array搜索数组值,但您正在向它传递数组键。

You code can be simplified with isset and ternary if: 如果满足以下条件,则可以使用isset和三进制简化代码:

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

You want: 你要:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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