0

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
5
  • 2
    First $d !=null should be !is_null($d). And in_array($name, $d) should be isset($d[$name]). Commented Aug 6, 2014 at 13:43
  • 2
    It should be $d !== null, if anything. One does not need an unnecessary overhead. Commented Aug 6, 2014 at 13:45
  • In fact you could just do isset since it returns false on null as well. Commented Aug 6, 2014 at 13:46
  • 1
    Are you confusing keys with values? in_array() is searching for a value; but you're return assumes that it's a key Commented Aug 6, 2014 at 13:46
  • Please read what in_array actually does. Commented Aug 6, 2014 at 13:47

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

You want:

if (isset($d[$name]))
 return $d[$name];
else
 return null;
answered Aug 6, 2014 at 13:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.