0

This is my array in PHP:

$arr['key1']='value1';
$arr['key2']='value2';
$arr['key3']='value3';
$arr['key4']='value4';
$arr['key5']='value5';
$arr['key6']='value6';

I would like to test if a key is in the array. Is this function the correct way to proceed?

function isKeyInArray($key, $arr) {
   if(isset($arr[$key]))
      return true;
   else
      return false;
}

What I expect is that:

isKeyInArray('key3', $arr) // return true
isKeyInArray('key9', $arr) // return false

Many thanks in advance.

3
  • so whats the problem? correct way to proceed? nothing wrong with this Commented Sep 29, 2014 at 8:28
  • How about testing it? Commented Sep 29, 2014 at 8:29
  • 1
    Why don't you use array_key_exists()? Commented Sep 29, 2014 at 8:29

4 Answers 4

6

You can use array_key_exists.

$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }

See http://php.net/manual/en/function.array-key-exists.php

Sign up to request clarification or add additional context in comments.

1 Comment

@UBEX,This code will perform the task as well. But I'll recommend you to use the function you have written yourself as it will give you confidence to write code yourself instead asking here.
4

Use array_key_exists

if(array_key_exists('key6',$arr))
   echo "present";
else
   echo "not present";

Comments

2

Using isset() is good if you consider that null is not a suitable value. Also isset is faster than array_key_exists.

$a = [ 'one' => 1, 'two' => null ];
isset($a['one']); // true
isset($a['two']); // false
array_key_exists('two', $a); // true

Comments

0

Use php function array_key_exists('key3', $a);

First google your need and only after that you can use your own function. This will save lots of your time.

Comments

Your Answer

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.