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?
asked Aug 6, 2014 at 13:42
124697
22k69 gold badges198 silver badges320 bronze badges
2 Answers 2
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;
}
answered Aug 6, 2014 at 13:51
Steve
20.5k5 gold badges47 silver badges71 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You want:
if (isset($d[$name]))
return $d[$name];
else
return null;
answered Aug 6, 2014 at 13:49
Zebra North
11.5k7 gold badges40 silver badges50 bronze badges
Comments
lang-php
$d !=nullshould be!is_null($d). Andin_array($name, $d)should beisset($d[$name]).$d !== null, if anything. One does not need an unnecessary overhead.issetsince it returns false on null as well.in_array()is searching for a value; but you're return assumes that it's a keyin_arrayactually does.